zoukankan      html  css  js  c++  java
  • 找出给定的一个字符串中最长的不重复子串,不重复子串即一个子串中不出现两个相同的字符

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

    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;
      }

    }

  • 相关阅读:
    IsDefined的问题
    设计匠艺模型
    真实案例引起的对系统健壮性的思考
    软件系统的稳定性
    LA工作第二周体会
    LA工作第一周体会
    https://blog.csdn.net/qq_26264237/article/details/90575165
    Maven项目配置logback
    Java 工具 Hutool4.0.0 正式发布:从懵懂到成熟
    IDEAidea中解决Java程序包不存在问题
  • 原文地址:https://www.cnblogs.com/huaiyinxiaojiang/p/6900828.html
Copyright © 2011-2022 走看看