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

思路:

定义两个指针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;
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值