首页 > 其他 > 详细

LeetCode 3: Longest Substring Without Repeating Characters

时间:2015-03-23 01:41:40      阅读:236      评论:0      收藏:0      [点我收藏+]

题目描述:

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

思路:

题目要求一个字符串中最长的没有重复字符的字符串长度,很明显可以用哈希表来实现,对出现的字符,哈希表中置1,两个指针一个指向头一个指向尾。并记录最长的没有重复字符的最长字符串的长度。

 

代码:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
		int start = 0;
		int tail = 0;
		map<char,int> map_str;
		int max = 0;
		int count = 0;
		while(start<s.size()&&tail<s.size()){
			if(map_str[s[tail]]==0){
				map_str[s[tail]]++;
				count ++;
				tail++;
				if(max<count){
					max = count;
				}
			}else{
				map_str[s[start]]--;
				start++;
				count--;
			}
		}
		return max;
	}
};

 

LeetCode 3: Longest Substring Without Repeating Characters

原文:http://www.cnblogs.com/xiamaogeng/p/4358533.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!