码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 记录之求最长子串

时间:2017-07-10 10:23:50      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:ast   idea   position   ash   already   keep   ready   substr   turn   

//the basic idea is, keep a hashmap which stores the characters in string as keys and their positions as values, and keep two pointers which define the max substring. move the right pointer to scan through the string , and meanwhile update the hashmap. If the character is already in the hashmap, then move the left pointer to the right of the same character last found. Note that the two pointers can only move forward.
//每个数组里保留的值都是字符最新的位置,用一个数值保存字符的位置,一个数值保存最长子串的长度,如果当前字符串位置比之前字符串位置大,则保留当前位置,否则记录之前的位置,递归求出最大子串的长度
int longestsubstring(string s)
{
	vector<int>CharRecoder(256,-1);
	int maxLength,c=0;
	for (int i=0;i<s.size();i++)
	{
		c=max(CharRecoder[s[i]]+1,c);
		CharRecoder[s[i]]=i;
		maxLength=max(maxLength,i-c+1);
	}
	return maxLength;
}

  

LeetCode 记录之求最长子串

标签:ast   idea   position   ash   already   keep   ready   substr   turn   

原文地址:http://www.cnblogs.com/fanchaostudy/p/7144036.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!