題目要求我們得出不含重復元素子串的最大長度。 解題思路: 一開始使用暴力破解法(兩遍for循環),結果直接TimeLimit .后面查看官方答案,感到柳暗花明。
代碼解釋: 首先,定義了一個256大小的int數組map,用于對應于256位ASCII碼,接下來,在for循環中用了一個while語句,j從0開始依次往后漸增,當s.charAt[j]是第一次出現,便將map[s.charAt(j)]賦值1(一開始map[]數組初始化為0),當第二次出現前面的元素時while語句的map[s.charAt(j)]==0條件不再滿足,此時while語句跳出執行下一次for循環語句,便把之前的 map[s.charAt(i)] = 0。如果,之前的引起while語句跳出的因素仍未消除j將繼續卡在原來的那一步,并重復上述操作。最后得到答案。
參考答案:
public int lengthOfLongestSubstring(String s) { int[] map = new int[256]; // map from character's ASCII to its last occured index int j = 0; int i = 0; int ans = 0; for (i = 0; i < s.length(); i++) { while (j < s.length() && map[s.charAt(j)]==0) { map[s.charAt(j)] = 1; ans = Math.max(ans, j-i + 1); j ++; } map[s.charAt(i)] = 0; //釋放元素,達到解除j卡死因素的目的 } return ans;
|
新聞熱點
疑難解答