如何计算无重复字符的最长子串

   题目如下:

   

  关于这个问题,我思考过几个小时,开始用了3个嵌套循环,但是这个时间复杂度太高了是O(n3),长度为100的,需要遍历100*100*100=1000000次,时间太长了,后来思考再三,思考能不能只用一个for循环来解决,下面思路:

  1.定义一个StringBuilder存储字符,从第一位遍历的字符开始。

  2.定义一个最长子串长度变量max=0;

  3.把字符加入StringBuilder时判断如果这个新的字符已经在StringBuilder中存在,就删除从0到这个新的字符所在StringBuilder位置的长度(+1),然后再加上新的字符。

  4.每次遍历都把StringBuilder的长度与max进行对比,如果比max长就赋值给max。

  代码如下:

    

 1 class Solution {
 2     public int lengthOfLongestSubstring(String s) {
 3         int length = s.length();
 4         int max = 0;
 5         StringBuilder temp = new StringBuilder();
 6         for (int i = 0; i < length; i++) {
 7           String tempS = String.valueOf(s.charAt(i));
 8           int tempIndex = temp.indexOf(tempS);
 9           if (tempIndex >= 0) {
10             temp = temp.delete(0, tempIndex + 1).append(tempS);
11           } else {
12             temp = temp.append(tempS);
13           }
14           int tempMax = temp.length();
15           if (tempMax > max) {
16             max = tempMax;
17           }
18         }
19         return max;
20     }
21 }
View Code

   如有更好思路的朋友,欢迎多多交流。

原文地址:https://www.cnblogs.com/wuyouwei/p/10780149.html