Longest Substring Without Repeating Characters

Description:

Given a string, find the length of the longest substring without repeating characters.

Examples:

  1. Given "abcabcbb", the answer is "abc", which the length is 3.
  2. Given "bbbbb", the answer is "b", with the length of 1.
  3. 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.

思路:

利用HashMap,把字符當(dāng)做key,把字符最后出現(xiàn)的index當(dāng)做value存在map中,儲存的過程其實就是在對字符串的遍歷,當(dāng)發(fā)現(xiàn)重復(fù)的字符時,更新結(jié)果。

Solution

public int longest_substring_without_repeating(String s){
  int result = 0;
  HashMap<Character, Integer> map = new HashMap<>(); //store the current index of the character
  for(int i = 0, j = 0; j < s.length(); j++){
    char cur_char = s.charAt(j);
    if(map.containsKey(cur_char)){
      i = Math.max(i, map.get(cur_char)+1);
    }
    map.put(cur_char, j);
    result = Math.max(result, j - i + 1);
  }
  return result;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容