LeetCode 3. Longest Substring Without Repeating Characters
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.
【题目分析】
给定一个字符串,求出其包含的最长的子串的长度。
【思路】
我们设置一个数组来记录以当前字符串结尾的子串的长度,然后遍历数组找出最长的子串即可。那么如果来计算以每一个字符串结尾的子串的长度呢?
以"abcabcbb"为例:
1. 初始时以每一个字符串结尾的子串的长度设置为0
2. 构造一个Map用来保存已经遍历到的字符,初始时仅包含第一个字符 {}
3. 从第一个字符开始遍历,如果map中没有包含该字符,那么subStringLengthEndWithCurChar = subStringLengthEndWithLastChar + 1.
如果map中已经有该字符,我们看一下它是否包含在以上一个字符结尾的子串当中,如果包含:那么以上个子串结尾的字符串从上一个当前字符处截断,然后长度加1,否则的话:继续在上个字符串的基础上长度加1.
4. 开始遍历
5.map = {(a,0)}
6. map = {(a,0),(b,1)}
7. map = {(a,0),(b,1),(c,2)}
8. map = {(a,3),(b,1),(c,2)}
9. map = {(a,3),(b,4),(c,2)}
10. map = {(a,3),(b,4),(c,5)}
11. map = {(a,3),(b,6),(c,5)}
12. map = {(a,3),(b,7),(c,2)}结束
【java代码】
1 public class Solution { 2 public static int lengthOfLongestSubstring(String s) { 3 if(s.length() <= 0) return 0; 4 int[] lengthNum = new int[s.length()]; 5 Map<Character, Integer> index = new HashMap<>(); 6 7 int max = 0; 8 for(int i = 0; i < s.length(); i++) { 9 if(!index.containsKey(s.charAt(i))) { 10 lengthNum[i] = lengthNum[i-1] + 1; 11 } 12 else if(i - index.get(s.charAt(i)) <= lengthNum[i-1]) { 13 lengthNum[i] = i - index.get(s.charAt(i)); 14 } 15 else{ 16 lengthNum[i] = lengthNum[i-1] + 1; 17 } 18 index.put(s.charAt(i), i); 19 } 20 for(int i = 0; i < s.length(); i++) { 21 max = Math.max(max, lengthNum[i]); 22 } 23 return max; 24 } 25 }