字符串找出其中字母不重复连续的最大子串

2025-10-10 13:46:34

java实现:给定一个字符串 找出其中字母不重复连续的最大子串

工具/原料

IDEA2019

JAVA1.8

方法/步骤

public class NoRepeatString {

 

   /**

 

    * 找出字符串中连续不重复最大字串

 

    *

 

    * @param params

 

    * @return

 

    */

 

   public Map<Integer,String> withoutNoRepeat(String params){

 

       //存放结果 长度和字符

 

       Map<Integer,String> result = new HashMap<>(16);

 

       //中间过程map 存放字符和字符对应位置

 

       Map<String,Integer> temp = new HashMap<>(16);

 

       //指针开始位置

 

       int startIndex = 0;

 

       //指针结束位置

 

       int endIndex = 0;

 

       //最大长度

 

       int maxLength = 0;

 

       //截取字符串

 

       String resultStr = "";

 

       for(int i=0;i<params.length();i++){

 

           //查看字符串在map中是否存在

 

           String singleChar = String.valueOf(params.charAt(i));

 

           if(temp.get(singleChar) != null){

 

               //指针开始位置移到这里

 

               if(temp.get(singleChar) > startIndex){

 

                   startIndex = temp.get(singleChar);

 

               }

 

           }

 

           //指针后移一位

 

           endIndex++;

 

           //将字符放入临时map

 

           temp.put(singleChar, i+1);

 

           if(endIndex - startIndex > maxLength){

 

               //长度比maxLength的大 maxLength重新赋值

 

               maxLength = endIndex - startIndex;

 

               //得到最长字串

 

               resultStr = params.substring(startIndex, endIndex);

 

           }

 

       }

 

       //返回结果

 

       result.put(maxLength,resultStr);

 

       return result;

 

   }

 

}

单元测试:

public class TestNoRepeatString {

 

   @Test

 

   public void noRepeatStr(){

 

       String str = "defdefabc";

 

       NoRepeatString noRepeatString = new NoRepeatString();

 

       Map<Integer, String> integerStringMap = noRepeatString.withoutNoRepeat(str);

 

       integerStringMap.forEach((key,value) -> System.out.println("最大字串长度:" + key + ";" + "最大字串为:" + value));

 

   }

 

}

执行结果:

最大子串长度:6;最大子串为:defabc

Process finished with exit code 0

字符串找出其中字母不重复连续的最大子串

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢