美文网首页
Longest Substring Without Repeat

Longest Substring Without Repeat

作者: EIP_Miracle | 来源:发表于2017-10-22 16:00 被阅读0次

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<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;
}

相关文章

网友评论

      本文标题:Longest Substring Without Repeat

      本文链接:https://www.haomeiwen.com/subject/vhgwuxtx.html