找出给定的一个字符串中最大的不重复子串,不重复子串即一个子串中不出现两个相同的字符

Posted 蒋闯

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了找出给定的一个字符串中最大的不重复子串,不重复子串即一个子串中不出现两个相同的字符相关的知识,希望对你有一定的参考价值。

思路一:先找出一个字符串中所有子串,再找出所有子串中最长的那一个;
思路二:每次找出的子串长度都比上一次的子串长,则最后的子串即是最长子串的长度数。
我选择的是第二种方法。

public class FindSubstringMaxlengthNoduplicate {
  public static void main(String[] args) {
  String s = "adcdghcwioizhfksjdyuiodfhjskhgkhgeisdcjdkh";
  ArrayList<String> result = findMaxLength(s);
  int maxLength = result.get(result.size()-1).length();
  System.out.println("最长不重复子串为:");
  for(String r : result){
    if(r.length() == maxLength){
      System.out.println(r);
    }
  }
}

private static ArrayList<String> findMaxLength(String s) {
  int maxLength = 0;
  HashSet<Character> hs = null;
  ArrayList<String> list = new ArrayList<String>();
  for(int j = 0; j < s.length(); ++j){
    int count = 0;
    hs = new HashSet<Character>();
    for(int i = j; i < s.length(); ++i){
      if(hs.add(s.charAt(i))){
        ++count;
        if(count == s.length()-j){
           if(count >= maxLength){
              maxLength = count;
              list.add(s.substring(j,i));
           }
           j = s.length();
        }
      }else{
        if(count >= maxLength){
          maxLength = count;
          list.add(s.substring(j,i));
        }
        int numOfDupllicate = 0;
        for(int k = j; k < i; ++k){
          if(s.charAt(i) != s.charAt(k)){
            ++numOfDupllicate;
          }else{
            break;
          }
        }
        j = j+numOfDupllicate;
        break;
        }
      }
    }
    return list;
  }

}

以上是关于找出给定的一个字符串中最大的不重复子串,不重复子串即一个子串中不出现两个相同的字符的主要内容,如果未能解决你的问题,请参考以下文章

459. 重复子字符串(Python)

求两个输入的字符串的最长公共子串

leetcode-03给定一个字符串,请你找出其中不含有重复字符的最长子串的长度

最长不重复子串

给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度

给定一个字符串,请你找出其中不含有重复字符的 最长子串的长度