標籤:標記 without sub hashmap bcb seq which ash contains
3. Longest Substring Without Repeating Characters
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.
問題:
給定一個字串,找到最長的子串的長度沒有重複字元。
執行個體:
“abcabcbb”,答案是“ABC”,它的長度是3。
“bbbbb”,答案是“B”,長度為1。
“pwwkew”,答案是“wke”,以3的長度。注意,答案必須是一個字串,“pwke”是子串。
實現方式:
1.擷取字串長度
2.紀錄當前值為左標記
3.判斷當前字母是否出現過,若出現過就更新當前位置為新的左標記
4.如果當前 值比res大則更新res長度
方法:使用HashMap這樣,遇到重複就跳過迴圈,節約時間和空間
1 public class Solution { 2 public int lengthOfLongestSubstring(String s) { 3 Map<Character,Integer> map =new HashMap<>(); 4 int res =0,len=s.length(); 5 for(int i=0,j=0;j<len;j++){ 6 if(map.containsKey(s.charAt(j))){ 7 i=Math.max(map.get(s.charAt(j)),i); 8 } 9 map.put(s.charAt(j),j+1);10 res =Math.max(j-i+1,res) ;11 }12 return res;13 }14 }
3. Longest Substring Without Repeating Characters【leetcode】java,演算法,Substring實現,子串,HashMap