標籤:
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 處,再進行計算最大間距。
Leetcode 詳解(Substing without repeats character)