p3

LeetCode p3 Longest Substring Without Repeating Characters 题解

1.题目:

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.

题意:

输入一个字符串,返回这个字符串中最长的没有包含重复元素的子串。

2.解题思路:

用HashMap记录出现的字符,出现重复的则以下一个元素为起点。

3.代码


[title] [] [url] [link text]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 
public class Solution {
public int lengthOfLongestSubstring(String s) {
int j = 0;
int max = 0;
HashMap<Character, Integer> hashMap = new HashMap<Character, Integer>();
if (s.length() < 1)
return 0;
for (int i = 0; i < s.length(); i++) {
char a = s.charAt(i);
if (hashMap.containsKey(a)) {
j = Math.max(j, hashMap.get(a) + 1); // 以重复元素的下一个元素为起点
}
hashMap.put(a, i);
max = Math.max(max, i + 1 - j);
}
return max;
}
}

4.一些总结: