求字符串中重复字符的最大间隔

来源:互联网 发布:周立功编程器 5000u 编辑:程序博客网 时间:2024/05/24 07:01

思路:

定义两个指针pStr1和pStr2分别指向字符串的头和尾。定义map<char,int> strMap,保存字符和对应的最大间隔。保持pStr1不变,如果pStr1和pStr2指向的字符相等,则在strMap中保存strMap[str[pStr1]] = pStr2 - pStr1; 否则pStr2递减直到终止条件pStr1 < pStr2。注意每次遍历前都要判断str[pStr1]是否在strMap中,如果在的话就直接进入下一个循环。最后遍历strMap,找出最大的value值。


/* 求字符串中重复字符最大的间隔*/#include <stdio.h>#include <iostream>#include <string>#include <map>using namespace std;int GetMaxInterval(string str);int main(){string str;while (str != "exit"){cout << "input string:";//cin >> str;  //不包含空格getline(cin, str);  //包含空格//cout << str;cout << "Max interval is: " << GetMaxInterval(str) << endl;}system("pause");return 0;}int GetMaxInterval(string str){int lenStr = str.length();//cout << lenStr << endl;if (lenStr <= 1)return 0;//int pStr1 = 0;int pStr2 = lenStr - 1;map<char, int> strMap;map<char, int>::iterator iter;for (int pStr1 = 0; pStr1 < lenStr - 1; ++pStr1){iter = strMap.find(str[pStr1]);if (iter == strMap.end())  //strMap中没有键存在{while (pStr1 < pStr2){if (str[pStr1] == str[pStr2])  //找{strMap[str[pStr1]] = pStr2 - pStr1;break;}pStr2 -= 1;}pStr2 = lenStr - 1;}}int result = 0;for (iter = strMap.begin(); iter != strMap.end(); ++iter){if ((iter->second) > result){result = iter->second;}}return result;}