求一个字符串的最长的无重复子串

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012017783/article/details/82591542

例如,在”abcabcbb”中,其无重复字符的最长子字符串是”abc”,其长度为 3。

对于,”bbbbb”,其无重复字符的最长子字符串为”b”,长度为1。

import java.util.HashSet;
import java.util.Scanner;

public class Main {

    /**
     * 获得最长的无重复子串(滑动窗口的思想)
     * @param str
     * @return
     */
   public static int getLongestStr(String str){
       if(str==null||str.length()==0)
         return 0;
       int len=str.length();
       HashSet<Character>set=new HashSet<>();
       int res=0,i=0,j=0;
       String temp="";
       while(i<len&&j<len){
           if(!set.contains(str.charAt(j))){

               set.add(str.charAt(j++));
              // res=Math.max(res, j-i);
               if(j-i>res){
                   res=j-i;
                   temp=str.substring(i,j);
               }

           }else{
               set.remove(str.charAt(i++));
           }   
       }
       System.out.println(temp);
       return res;
   }

   public static void main(String[] args) {
     Scanner sin=new Scanner(System.in);

     while(sin.hasNext()){

          String str=sin.nextLine();

          System.out.println(getLongestStr(str));

     }

  }
}

这里写图片描述

猜你喜欢

转载自blog.csdn.net/u012017783/article/details/82591542