zoukankan      html  css  js  c++  java
  • LeetCode3 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^2),last[s.charAt(i)]记录i位置的字符向前找第一次出现的位置,pre相当于向前找时不可翻过的"墙",每次找到相同的字符要跟新这个"墙"的位置,pre是尽量靠后.

     public static int lengthOfLongestSubstring(String s) {
            final int N=255;
            int[] last=new int[N];  //记录一个字母上次出现的最近的位置
            int ansLength=0;
            for(int i=0;i<s.length();i++){
                last[s.charAt(i)]=-1;
            }
            int pre=-1;  //每个字符向前找
            for(int i=0;i<s.length();i++){
                for(int j=i-1;j>pre;j--){
                    if(s.charAt(j)==s.charAt(i)){
                        last[s.charAt(i)]=j;
                        break;
                    }
                }
                if(last[s.charAt(i)]<i&&last[s.charAt(i)]>pre){
                    pre=last[s.charAt(i)];
                }
                ansLength=Math.max(ansLength,i-pre);
            }
            return ansLength;
        }
    View java Code

    http://blog.csdn.net/feliciafay/article/details/16895637有运行时间为O(n)复杂度的代码

    int lengthOfLongestSubstring(string s) {
      int n = s.length();
      int i = 0, j = 0;
      int maxLen = 0;
      bool exist[256] = { false };
      while (j < n) {
        if (exist[s[j]]) {
          maxLen = max(maxLen, j-i);
          while (s[i] != s[j]) {
            exist[s[i]] = false;
            i++;
          }
          i++;
          j++;
        } else {
          exist[s[j]] = true;
          j++;
        }
      }
      maxLen = max(maxLen, n-i);
      return maxLen;
    }
    View Code

    外层while在改变j的值,j最多从0改变到n(n为字符串的长度),内层while在改变i的值,同样的,i最多从0改变到n(n为字符串的长度)。所以加起来,时间复杂度为O(2*N),也就是O(N)。

    还可以这样想,内层循环不一定要进行的,仅仅当j遇到了重复字符后需要更新i的值时,才会进行内存循环,而且i加起来走过的步数最多为n(n为字符串的长度)。

    这段代码还有很有意思的一点,就是别忘了在循环体之外,还要写上,maxLen = max(maxLen, n-i)。这是为什么呢? 因为可能最后一次检查的时候,j知道走到字符串末尾都没有遇到重复字符。而while循环体中找到的最长不重复子串只是在j遇到重复字符时才进行的。

  • 相关阅读:
    加壳技术
    1002 ( A + B Problem II )
    1000 ( A + B Problem )
    1001 ( Sum Problem )
    背单词Delphi版
    覆盖Form.WndProc来响应消息
    覆盖Dispatch响应消息
    美丽人生论坛看贴工具delphi版
    TWebBrowser组件在DELPHI中POST数据和取得网页源文件
    读淘宝商品描述页源码delphi版
  • 原文地址:https://www.cnblogs.com/duanqiong/p/4409485.html
Copyright © 2011-2022 走看看