找出字符串的最长不重复子串

来源:互联网 发布:爱福窝win7软件下载 编辑:程序博客网 时间:2024/05/21 22:45
  1. 题目:找出字符串的最长不重复子串,输出最长子串

 

思路:维持两个数组:Start[]和All[],
分别记录,从当前的字符为起始的子串的最长值,和当前字符后面的最长子串长度。

在向前遍历时,当有重复字符出现时,更新相应的长度值,
即,更新Start[curIndex]为从当前点,到那个已经存在的重复字符之前的长度;
All[curIndex]也要做相应调整。

比较:Max(Start[curIndex], All[curIndex]);

 

若当前点不重复,Start[Cur] = 1+Start[Cur+1];
All[Cur] = Max(Start[Cur], All[Cur+1]);

若重复,
Start[Cur] = 到重复节点前的长度,可以通过hash辅助实现;
All[Cur] = Max(Start[Cur], All[Cur+1]);

最后,All[0]应该就是结果;

 

缺点:对于bcdefb,最长字串有两种选择

 

  1. public static CharSequence maxNotRepSubStr(char[] ch, int st, int end) {
      if (end - st == 1)
       return new String(ch);
      int[] start = new int[end];
      int[] all = new int[end];
      int[] sub = new int[end];
      HashMap<Character, Integer> hash = new HashMap<Character, Integer>();
      start[end-1] = 1;
      all[end-1] = 1;
      sub[0]  = end-1;
      hash.put( ch[end-1], end-1);
      int curStart = end-1;
      int maxNum = 1;
      for (int k = end - 2; k >= st; k--) {
       Integer in = hash.get(ch[k]);
       if (in == null) {
        start[k] = start[k + 1]+1;
        if (start[k] > all[k + 1]) {
         all[k] = start[k];
         sub[0] = k;
         sub[1] = curStart;
        } else {
         all[k] = all[k + 1];
        }
       } else {
        all[k] = all[k + 1];
        start[k] = 1;
        curStart = k;
       }
       hash.put(ch[k], k);
      }
      System.out.println(new String(ch, sub[0], all[0]));
      return new String(ch, sub[0], sub[1]);
     }