leetcode--3--最长不重复字符串
2016-09-30 13:27
260 查看
原题:Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is
a subsequence and not a substring.
解答:
C++版本
<span style="font-size:24px;"><span style="font-family:Times New Roman;">int lengthOfLongestSubstring(string s) { vector<int> dict(256, -1); int maxLen = 0, start = -1; for (int i = 0; i != s.length(); i++) { if (dict[s[i]] > start) start = dict[s[i]]; dict[s[i]] = i; maxLen = max(maxLen, i - start); } return maxLen; }</span></span>
Java版本
<span style="font-size:24px;"><span style="font-family:Times New Roman;"> public int lengthOfLongestSubstring(String s) { if (s.length()==0) return 0; HashMap<Character, Integer> map = new HashMap<Character, Integer>(); int max=0; for (int i=0, j=0; i<s.length(); ++i){ if (map.containsKey(s.charAt(i))){ j = Math.max(j,map.get(s.charAt(i))+1); } map.put(s.charAt(i),i); max = Math.max(max,i-j+1); } return max; }</span></span>
注意:
1、map.put(s.charAt(i),i),当s.charAt(i)重复时,i值会得到更新,如map中已经存在
(e,2),当执行map.put(e,3)时,原来的(e,2)变为(e,3)。
2、j = Math.max(j,map.get(s.charAt(i))+1),比较重复的位置,很重要,如果位置在j之前,则不需要更新j。
相关文章推荐
- LeetCode Longest Substring Without Repeating Characters 找到最长不重复字符串
- leetcode第三题:求给定字符串中最长无重复子串的长度
- 【LeetCode题目记录-3】字符串中最长的没有重复字符的子串
- Leetcode-3 Longest Substring Without Repeating Characters 最长无重复字节字符串
- [leetcode]获取字符串中字符不重复的最长子串的长度
- leetcode【第十八周】以特定次数替换字符并计算最长重复字符串
- 从零打卡leetcode之day 4--无重复最长字符串
- 求字符串中最长无重复字符的子串
- 最长重复字串和两字符串中最长公子子串问题
- 找出字符串的最长不重复子串
- 在字符串中查找连续重复的最长子串的C++实现
- 【每日面试题】给定一个字符串,求出其最长的重复子串
- 字符串相关处理kmp,前缀数,后缀树,后缀数组,最长回文串,最长重复字串,最长非重复字串
- 求一个字符串中最长的非重复连续子串
- 给定一个字符串,求出其最长的重复子串
- 找出字符串中出现重复而且长度最长的字符串,并且输出而且输出其长度
- 编程珠玑(二)寻找一个字符串中最长重复字串
- [动态规划经典之二]求字符串的最长不重复子串(连续子序列)
- 求字符串中不含重复字符的最长子串的长度
- 在字符串中查找最长重复子串的探讨