(leetcode)3.一個數組的最長子列Longest Substring Without Repeating Characters--Java

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.
找到最長的子字符串,其思想是一次遍歷,兩個指針i和j,存在map中,如果沒有重複的,則直接+1,如果有重複的,則把j的位置後移,然後計算max


public int lengthOfLongestSubstring(String s)
{if(s.length()==0)return0;
HashMap<Character, Integer>map=newHashMap<Character, Integer>();
int max=0;
for(int i=0, j=0; i<s.length(); ++i){
if(map.containsKey(s.charAt(i)))
{ j = Math.max(j,map.get(s.charAt(i))+1);  //關鍵點:j只能往後走,不能往前看。
}
map.put(s.charAt(i),i);
max= Math.max(max,i-j+1);
}
return max;
}
發佈了32 篇原創文章 · 獲贊 17 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章