LeetCode - Longest Substring Without Repeating Characters hash

来源:互联网 发布:手机投影仪连接软件 编辑:程序博客网 时间:2024/06/05 10:03

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

[java] view plaincopy
  1. public class Solution {  
  2.     public int lengthOfLongestSubstring(String s) {  
  3.         if(s.isEmpty()) return 0;  
  4.         if(s.length() == 1return 1;  
  5.           
  6.         char[] sArray = s.toCharArray();  
  7.         int p1 = 0;  
  8.         int p2 = 1;  
  9.         HashSet<Character> bufferSubString = new HashSet<Character>();  
  10.         bufferSubString.add(sArray[p1]);  
  11.         int curMax = 0;  
  12.         while(p2 < sArray.length){  
  13.            if(bufferSubString.contains(sArray[p2])){  
  14.                if(p2 - p1 > curMax) curMax = p2 - p1;  
  15.                //move p1  
  16.                while(sArray[p1] != sArray[p2]){  
  17.                    bufferSubString.remove(sArray[p1]);  
  18.                    p1++;  
  19.                }  
  20.                bufferSubString.remove(sArray[p1]);  
  21.                p1++;  
  22.                bufferSubString.add(sArray[p1]);  
  23.                bufferSubString.add(sArray[p2]);  
  24.                p2++;  
  25.            } else {  
  26.                bufferSubString.add(sArray[p2]);  
  27.                p2++;  
  28.            }  
  29.         }  
  30.         if(p2 - p1 > curMax) curMax = p2 - p1;  
  31.         return curMax;  
  32.     }  
  33. }  
0 0
原创粉丝点击