LeetCode 3. 无重复字符的最长子串
2018-10-10 21:42
741 查看
题目描述:
给定一个字符串,找出不含有重复字符的最长子串的长度。
示例 1:
输入: "abcabcbb" 输出: 3 解释: 无重复字符的最长子串是 "abc",其长度为 3。
示例 2:
输入: "bbbbb" 输出: 1 解释: 无重复字符的最长子串是 "b",其长度为 1。
示例 3:
输入: "pwwkew" 输出: 3 解释: 无重复字符的最长子串是 "wke",其长度为 3。
代码实现:
暴力法:(超时)
[code]public class Solution { public int lengthOfLongestSubstring(String s) { int ans = 0; for(int i =0;i<s.length();i++){ for(int j = i+1;j<=s.length();j++){ //注意j的最大取值 if(allUnique(s,i,j)) ans = Math.max(ans,j-i); else break; } } return ans; } public boolean allUnique(String s,int start,int end){ Set<Character> set = new HashSet<>(); for(int i = start;i<end;i++){ Character c = s.charAt(i); if(set.contains(c)) return false; else set.add(c); } return true; } }
滑动窗口:
[code]public class Solution { public int lengthOfLongestSubstring(String s) { int ans = 0; int n = s.length(); Set<Character> set = new HashSet<>(); int i = 0 ,j =0; while(i<n&&j<n){ //如果s.charAt(j)已经重复了就不停的剔除前面的元素,直到一个新的set加上 s.charAt(j)不包含重复元素 if(!set.contains(s.charAt(j))){ set.add(s.charAt(j++)); ans = Math.max(ans,j-i); }else{ set.remove(s.charAt(i++)); } } return ans; } }
优化的滑动窗口
[code]public class Solution { public int lengthOfLongestSubstring(String s) { int n = s.length(), ans = 0; Map<Character, Integer> map = new HashMap<>(); // current index of character // try to extend the range [i, j] for (int j = 0, i = 0; j < n; j++) { if (map.containsKey(s.charAt(j))) { i = Math.max(map.get(s.charAt(j)), i); } ans = Math.max(ans, j - i + 1); map.put(s.charAt(j), j + 1); } return ans; } } public class Solution { public int lengthOfLongestSubstring(String s) { int n = s.length(), ans = 0; int[] index = new int[128]; // current index of character即下一次i直接跳到哪 // try to extend the range [i, j] for (int j = 0, i = 0; j < n; j++) { i = Math.max(index[s.charAt(j)], i); ans = Math.max(ans, j - i + 1); //i不变的话 j还没+1 所以ans需要+1 index[s.charAt(j)] = j + 1; } return ans; } }
阅读更多
相关文章推荐
- LeetCode 3. 无重复字符的最长子串
- LeetCode 3. 无重复字符的最长子串 Python
- Leetcode 3. 无重复字符的最长子串
- 【LeetCode】3. 无重复字符的最长子串(Longest Substring Without Repeating Characters,24.2%,中等)
- 【LeetCode】3.无重复字符的最长子串 结题报告 (C++)
- [LeetCode] Longest Substring Without Repeating Characters 无重复字符的最长子串
- LeetCode题库解答与分析——#3.无重复字符的最长子串LongestSubstringWithoutRepeatingCharacters
- [LeetCode]3. Longest Substring Without Repeating Characters寻找最长无重复字符的子串
- LeetCode 3 无重复字符的最长子串(哈希表或数组)
- leetcode:Longest Substring Without Repeating Characters (寻找最长无重复字符的子串)
- 3. 无重复字符的最长子串(O(N))
- LeetCode: 3_Longest Substring Without Repeating Characters | 求没有重复字符的最长子串的长度 | Medium
- 3. 无重复字符的最长子串
- [leetcode]Longest Substring Without Repeating Characters【最长不重复字符子串】
- 【leetcode】第3题:求最长不重复(字符不重复)的子串的长度
- 【中级算法】3. 无重复字符的最长子串
- [leetcode]无重复字符的最长子串
- 3.无重复字符的最长子串(Longest Substring Without Repeating Characters)
- 【LeetCode题目记录-3】字符串中最长的没有重复字符的子串
- Leetcode 刷题(python)之 无重复字符的最长子串