首页 > 代码库 > LeetCode - Longest Substring Without Repeating Characters
LeetCode - Longest Substring Without Repeating Characters
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.
思路分析:这题O(n)的思路需要用到双指针,由于只需要返回最长不含重复字符的子串长度,只需要贪心保存最长解即可。类似的变形还有“return Longest Substring with Repeating Characters”,也主要用贪心,其实比这题简单, 在某公司面试时遇到这题,可见很多公司算法面试题都是leetcode题目的变形题目甚至原题。具体的解法是,用p2和p1两个指针一前一后走,p1记录当前查看的子串首个字符,p2在前面如果扫到和p1对应的字符不同的字符就继续向前走,直到发现与p1字符相同的字符,停下来计算当前扫描的字串长度,更新curMax长度。然后p1向前走,知道发现一个和p2相同的字符,再向前一步排除掉这个重复的字符,这样p1就成为了下一个不含重复字符的子符串起点,接着p2可以继续向前走,以此类推,直到扫描完整个字符串,curMax里面就保存了最长的不含重复字符的子串。实现中用到了HashSet来keep track of当前扫描的子串,注意HashSet的内容也要时刻随着p1和p2的移动而变化。
AC Code
public class Solution { public int lengthOfLongestSubstring(String s) { if(s.isEmpty()) return 0; if(s.length() == 1) return 1; char[] sArray = s.toCharArray(); int p1 = 0; int p2 = 1; HashSet<Character> bufferSubString = new HashSet<Character>(); bufferSubString.add(sArray[p1]); int curMax = 0; while(p2 < sArray.length){ if(bufferSubString.contains(sArray[p2])){ if(p2 - p1 > curMax) curMax = p2 - p1; //move p1 while(sArray[p1] != sArray[p2]){ bufferSubString.remove(sArray[p1]); p1++; } bufferSubString.remove(sArray[p1]); p1++; bufferSubString.add(sArray[p1]); bufferSubString.add(sArray[p2]); p2++; } else { bufferSubString.add(sArray[p2]); p2++; } } if(p2 - p1 > curMax) curMax = p2 - p1; return curMax; } }
LeetCode - Longest Substring Without Repeating Characters