Leetcode- string/array - Longest Substring Without Repeating Characters
来源:互联网 发布:注册不带www域名 编辑:程序博客网 时间:2024/06/05 02:42
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.
思路:
首先定义一个队列记录没有重复的substring,然后定义一个map记录每个char出现的次数,然后开始遍历string s,依次将没有重复出现的字节保存到队列中,同时用map记录字节出现的次数。一旦检测到某字节已经出现,将队列里出现该字节之前(包括该字节)的记录全都pop出来,与此同时也要erase掉map中记录的字节出现次数(重复出现的那个字节不要erase掉,因为后面还要将这个字节加入到队列中构成新的没有重复的substring)。这时候新的substring长度为map的长度,只要出现substring长度大于保存的最大长度,就更新保存的最大长度。
class Solution {public: int lengthOfLongestSubstring(string s) { queue<char> charQue; map<char, int> charMap; int lenOfSub=0; int maxLen=0; for(int i=0;i<s.size();i++) { if(charMap[s[i]]>0) { while(charQue.front()!=s[i]) { charMap.erase(charMap.find(charQue.front())); charQue.pop(); } charQue.pop(); charQue.push(s[i]); lenOfSub=charMap.size(); } else { charMap[s[i]]++; charQue.push(s[i]); lenOfSub++; } if(lenOfSub>maxLen) maxLen=lenOfSub; } return maxLen; }};
class Solution {public: int lengthOfLongestSubstring(string s) { int maxLen=0; int index=-1; int record[256]; memset(record, -1, sizeof(int)*256); for(int i=0;i<s.size();i++) { if(record[s[i]]>index) index=record[s[i]]; if(i-index>maxLen) maxLen=i-index; record[s[i]]=i; } return maxLen; }};
0 0
- Leetcode- string/array - Longest Substring Without Repeating Characters
- [leetcode][string] Longest Substring Without Repeating Characters
- LeetCode-string-Longest Substring Without Repeating Characters
- leetcode 3---Longest Substring Without Repeating Characters 双指针 String
- String-3.Longest Substring Without Repeating Characters
- LeetCode: Longest Substring Without Repeating Characters
- LeetCode Longest Substring Without Repeating Characters
- LeetCode: Longest Substring Without Repeating Characters
- [Leetcode] Longest Substring Without Repeating Characters
- leetcode 23: Longest Substring Without Repeating Characters
- [LeetCode] Longest Substring Without Repeating Characters
- LeetCode 3 - Longest Substring Without Repeating Characters
- [LeetCode]Longest Substring Without Repeating Characters
- leetcode Longest Substring Without Repeating Characters
- 【leetcode】 Longest Substring Without Repeating Characters
- LeetCode-Longest Substring Without Repeating Characters
- [LeetCode] Longest Substring Without Repeating Characters
- [LeetCode] Longest Substring Without Repeating Characters
- C++数值类型极限值的获取
- 文件的操作
- Hibernate性能优化技巧
- linux下mysql区分大小写相关问题
- 找出我的前50有声读物
- Leetcode- string/array - Longest Substring Without Repeating Characters
- 怎样鞋360度的Flash动画都比较有影响力的客户
- nyoj 题目8 一种排序
- IE6中盒子绝对定位不起效果的解决方法
- adb push命令的使用
- 2014/8/7
- RTSP
- HDU 4928 Series 2
- 关于error:Cannot assign to 'self' outside of a method in the init family