原题地址:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
题目描述:
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: “abcabcbb”
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。
示例 2:
输入: “bbbbb”
输出: 1
解释: 因为无重复字符的最长子串是 “b”,所以其长度为 1。
示例 3:
输入: “pwwkew”
输出: 3
解释: 因为无重复字符的最长子串是 “wke”,所以其长度为 3。
请注意,你的答案必须是 子串 的长度,“pwke” 是一个子序列,不是子串。
解题方案:
我的解法:从头开始遍历,将暂时没有重复字符的子串存储,如果遇到重复字符就从存储子串中重复的那个字符的下一个字符开始算起。
class Solution {
public int lengthOfLongestSubstring(String s) {
int start = 0, count = 0, res = 0;
StringBuilder tmp = new StringBuilder();
for(int i = 0; i < s.length(); i ++)
{
if(tmp.indexOf(s.substring(i, i + 1)) == -1)
{
count ++;
tmp.append(s.charAt(i));
res = count > res ? count : res;
}
else
{
if(i == s.length() - 1)
return res;
start += tmp.lastIndexOf(s.substring(i, i + 1)) + 1;
res = count > res ? count : res;
tmp = new StringBuilder(s.substring(start, i + 1));
count = tmp.length();
}
}
return res;
}
}
大神解法:
建一个数组存储每个字符上次出现的位置,两个重复字符中间的串即不重复子串
class Solution {
public int lengthOfLongestSubstring(String str) {
if (str == null || str.equals("")) {
return 0;
}
char[] chars = str.toCharArray();
int[] map = new int[256];
for (int i = 0; i < 256; i++) {
map[i] = -1;
}
int len = 0;
int pre = -1;
int cur = 0;
for (int i = 0; i != chars.length; i++) {
pre = Math.max(pre, map[chars[i]]);
cur = i - pre;
len = Math.max(len, cur);
map[chars[i]] = i;
}
return len;
}
}