Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb"
, the answer is "abc"
, which the length is 3.
Given "bbbbb"
, the answer is "b"
, with the length of 1.
Given "pwwkew"
, the answer is "wke"
, with the length of 3. Note that the answer must be a substring, "pwke"
is a subsequence and not a substring.
我自己的代码:
public class Solution { public int lengthOfLongestSubstring(String s) { int slenmax=0; for(int i=0;i<s.length();i++) { int j=i+1; boolean flag=true; while(j<s.length()&&flag) { for(int k=i;k<j;k++) { if(s.charAt(j)==s.charAt(k)) { flag=false; j--; } } j++; } int slen=j-i; if(slen>slenmax) slenmax=slen; } return slenmax; } }
运行时可以通过,但是在提交时出现超时(思路比较简单,因而时间复杂度相应会比较高)
clean Code:
public class Solution { public int lengthOfLongestSubstring(String s) { boolean[] exist = new boolean[256]; //用表格处理,查找时会很快 int i = 0, maxLen = 0; for (int j = 0; j < s.length(); j++) { while (exist[s.charAt(j)]) { //这个while是精髓 exist[s.charAt(i)] = false; i++; } exist[s.charAt(j)] = true; maxLen = Math.max(j - i + 1, maxLen); } return maxLen; } }
注:借用了表的形式,把字符串中的字母依次存入表中并进行相应标记(如 exist[s.charAt(i)] = false;)。解决思路是:设定两个指针(i, j),都放在左头开始,从左到右,遇到有两个相同字母的情况,则计算两相同字母间距,更新最大间距,并且把i 也放在j 处,再进行计算最大间距。
时间: 2024-10-28 12:16:19