LeetCode-3:Longest Substring Without Repeating Characters (字符串最长子串)
题干:
Given a string, find the length of the longest substring without repeating characters.
给定一个字符串,求他的最长子串。
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc"
, with the length of 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b"
, with the length of 1.
Example 3:
Input: "pwwkew"
Output: 3
Explanation: 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.
解析:
借助一个整数数组用于存储已出现的字符的下标,字符对应的整数值作为下标,数组的值为元素在字符串chars中的下标,如:asdf,表示为 charIndex[97] = 0.
1. 初始化一个整数数组charIndex,大小为128(ASCII码最多128个不同的字符),数组值初始化为-1。
2. 从左向右滑动检查字符是否在charIndex数组中出现过(charIndex数组的值不等于-1)。
3. 如果字符未出现过,计入长度,并判定当前字符串长度是否大于历史上最大长度。
4. 如果出现过,重新计算剩余长度curLen,并将出现位置之前到滑动窗口起始位置的值设置为-1
提交结果:
Runtime: 31 ms, faster than 98.64% of Java online submissions for Longest Substring Without Repeating Characters.
源码(Java):
class Solution { public int lengthOfLongestSubstring(String s) { char[] chars = s.toCharArray(); int maxLen = 0; //存储当前找到的最长字符串 int curLen = 0; //存储当前不重复字符串长度 int[] charIndex = new int[128]; //ASCII一共128个字符 //初始化成-1 for (int i=0;i<charIndex.length;i++){ charIndex[i] = -1; } int pre = 0; for (int i=0;i<chars.length;i++){ int index = chars[i]; if (charIndex[index] >= 0){ //已经存在这个字符了 //判断如果长度是大于maxLen,则替换,否则不操作 if (curLen>maxLen){ // maxLen = curLen>maxLen?curLen:maxLen; maxLen = curLen; } //重新计算长度 curLen = i - charIndex[index]; //将之前的值置成0 int tmp = pre; pre = charIndex[index] + 1; //记录pre值 for (int j=charIndex[index];j>=tmp;j--){ charIndex[(int)chars[j]] = -1; } charIndex[index] = i; //记录字符串出现过 } else { //不存在已经出现的字符串 curLen ++; if (curLen>maxLen){ maxLen = curLen; } charIndex[index] = i; } } return maxLen; } }