3. Longest Substring Without Repeating Characters
官方的链接:3. Longest Substring Without Repeating Characters
Description :
Given a string, find the length of the longest substring without repeating characters.
Example:
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.
问题描述
给定一个字符串,找出最长不重复子串的长度
思路
建立一个128的数组,存储字符的下标,min存储非重复子串的最小下标,max存储最大下标。max逐步加大,如果下一个字符的下标大于min,则增加min,同时记录最大的max - min + 1
1 public class Q3_LongestSubstringWithoutRepeatingCharacters { 2 public int lengthOfLongestSubstring(String s) { 3 if (null == s || s.length() < 1) { 4 return 0; 5 } 6 // 初始化128的数组,足够存储所有字符 7 int[] intArray = new int[128]; 8 for (int i = 0; i < intArray.length; i++) { 9 intArray[i] = -1; 10 } 11 char num = s.charAt(0); 12 intArray[num] = 0; 13 int min = 0; 14 int max = 0; 15 int count = 1; 16 for (int i = 1; i < s.length(); i++) { 17 num = s.charAt(i); 18 max = i; 19 if (intArray[num] == (max - 1)) { 20 count = max - min > count ? max - min : count; 21 min = max; 22 } else if (intArray[num] >= min) { 23 count = max - intArray[num] > count ? max - intArray[num] : count; 24 min = intArray[num] + 1; 25 } else { 26 count = max - min + 1 > count ? max - min + 1 : count; 27 } 28 intArray[num] = i; 29 } 30 return count; 31 } 32 33 public static void main(String[] args) { 34 Q3_LongestSubstringWithoutRepeatingCharacters longest = new Q3_LongestSubstringWithoutRepeatingCharacters(); 35 System.out.println(longest.lengthOfLongestSubstring("nfpdmpi")); 36 } 37 }