Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

Leetcode:Longest Substring Without Repeating Characters 解题报告

SOLUTION 1:

http://blog.csdn.net/imabluefish/article/details/38662827

使用一个start来记录起始的index,判断在hash时 顺便判断一下那个重复的字母是不是在index之后。如果是,把start = map.get(c) + 1即可。并且即时更新

char的最后索引。

 1 public class Solution {
 2     public int lengthOfLongestSubstring(String s) {
 3         if (s == null) {
 4             return 0;
 5         }
 6         
 7         int max = 0;
 8         HashMap<Character, Integer> map = new HashMap<Character, Integer>();
 9         
10         int len = s.length();
11         int l = 0;
12         for (int r = 0; r < len; r++) {
13             char c = s.charAt(r);
14             
15             if (map.containsKey(c) && map.get(c) >= l) {
16                 l = map.get(c) + 1;
17             }
18             
19             // replace the last index of the character c.
20             map.put(c, r);
21             
22             // replace the max value.
23             max = Math.max(max, r - l + 1);
24         }
25         
26         return max;
27     }
28 }
View Code

相关文章:

  • 2022-12-23
  • 2021-07-08
  • 2021-12-09
猜你喜欢
  • 2021-12-18
  • 2021-11-13
  • 2021-10-15
  • 2022-02-26
  • 2021-12-05
  • 2021-11-18
  • 2021-08-16
相关资源
相似解决方案