当前位置: 代码迷 >> 综合 >> PTA1071 Speech Patterns(字符串操作)
  详细解决方案

PTA1071 Speech Patterns(字符串操作)

热度:52   发布时间:2023-11-08 14:36:40.0

分析:提取字符串问题。

注意防止字符串越界!应该是cur<len而不是cur<=len.

#include <iostream> 
#include <cstdio>
#include <string>
#include <stack>
#include <cstring>
#include <vector>
#include <queue>
#include <set> 
#include <map> 
#include <sstream>
#include <cmath> 
#include <algorithm> 
using namespace std;
string s1;
map<string, int> mp;
bool judge(char ch) {
    if (ch >= '0'&&ch <= '9') return true;if (ch >= 'a'&&ch <= 'z') return true;if (ch >= 'A'&&ch <= 'Z') return true;return false;
}
int main() {
    getline(cin, s1);int len = s1.length();int sta, cur = 0;bool flag = false;string s2 = s1;while (cur < len) {
      // 此处需要修改,当cur==len时,字符串访问越界while (!judge(s1[cur])) {
    cur++;}if (cur > len) break;//now cur point to charsta = cur;while (judge(s1[cur])) {
    cur++;if (cur >= len) {
     break; }  // 同理此处需要修改,当cur==len时,字符串访问越界,需要提前break}//if (cur > len) break;s2 = s1.substr(sta, cur - sta);for (int i = 0; i < s2.length(); i++) {
    if (s2[i] >= 'A'&&s2[i] <= 'Z') {
    s2[i] = s2[i] - 'A' + 'a';}}if (mp.find(s2) == mp.end()) {
    mp[s2] = 1;}else {
    mp[s2]++;}}map<string, int>::iterator ite;string k = s1;int maxx = -1;for (ite = mp.begin(); ite != mp.end(); ++ite) {
    if (ite->second > maxx) {
    maxx = ite->second;k = ite->first;}// cout<<ite->first<<" "<<ite->second<<endl;;}cout << k << " " << maxx << endl;return 0;
}

分析:段错误。一般都是应为数组越界,数组开的太大了原因。

#include<bits/stdc++.h>
#define inf 0x3f3f3f
using namespace std;
string s1;
map<string,int> mp;
bool judge(char ch){
    if(ch>='0'&&ch<='9') return true;if(ch>='a'&&ch<='z') return true;if(ch>='A'&&ch<='Z') return true;return false;
}
int main(){
    getline(cin,s1);int len=s1.length();int sta,cur=0;bool flag=false;string s2=s1;while(cur<=len){
       //此处需要修改,当cur==len时,字符串访问越界while(!judge(s1[cur])){
    cur++;}if(cur>=len) break;			//此处需要修改,当cur==len时,字符串访问越界sta=cur;while(judge(s1[cur])){
    cur++;if(cur>=len){
    break;}//不是大于等于,这里发生了数组越界问题。}s2=s1.substr(sta,cur-sta);for(int i=0;i<s2.length();i++){
    if(s2[i]>='A'&&s2[i]<='Z'){
    s2[i]=s2[i]-'A'+'a';}}if(mp.find(s2)==mp.end()){
    mp[s2]=1;}else{
    mp[s2]++;}}map<string,int>::iterator ite;string k=s1;int maxx=-inf;for(ite=mp.begin();ite!=mp.end();++ite){
    if(ite->second>maxx){
    maxx=ite->second;k=ite->first;}// cout<<ite->first<<" "<<ite->second<<endl;;}cout<<k<<" "<<maxx<<endl;return 0;
}
  相关解决方案