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遇到重复字符时才进行的。

  • 相关阅读:
    VOIP开源项目源码地址(一)
    iptables下udp穿越实用篇
    function socket about http://net.pku.edu.cn/~yhf/linux_c/function/14.html
    IOKE的SIP协议专栏
    XviD core API overview: Decoding
    Socket about
    sql海量数据优化
    Socket、多线程、消息队列、共享资源并发下的性能研究
    【转】SQL 索引理解
    SQL 索引理解
  • 原文地址:https://www.cnblogs.com/duanqiong/p/4409485.html
Copyright © 2011-2022 走看看