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,把字符当做key,把字符最后出现的index当做value存在map中,储存的过程其实就是在对字符串的遍历,当发现重复的字符时,更新结果。

Solution

public int longest_substring_without_repeating(String s){
  int result = 0;
  HashMap 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;
}

你可能感兴趣的:(Longest Substring Without Repeating Characters)