[leetcode]3-Longest Substring Without Repeating Characters
Posted NovaCN
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode]3-Longest Substring Without Repeating Characters相关的知识,希望对你有一定的参考价值。
3. Longest Substring Without Repeating Characters
1)题目
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.
2)思路
先写一个子函数,输入数组下标,母字符串,往后遍历,获得下标出最长子串长度。
遍历母字符串,调用子函数,获得每一位长度,放入数组里。
获取数组最大值。
3) 代码
public int lengthOfLongestSubstring(String s) {
if("".equals(s)||s==null){
return 0;
}
int[] len = new int[s.length()];
for (int i = 0; i < s.length(); i++) {
len[i]=getLongSubString(i,s);
}
int asInt = Arrays.stream(len).max().getAsInt();
return asInt;
}
private int getLongSubString(int i, String s) {
String sb = String.valueOf(s.charAt(i));
for (int j = i+1; j < s.length(); j++) {
if (sb.contains(String.valueOf(s.charAt(j)))) {
return j - i ;
}else {
sb += s.charAt(j);
}
}
return s.length()-i ;
}
4) 结果
时间复杂度:O(n^2)
空间复杂度:O(n)
耗时:326 ms
5) 调优
v2
其实只用一次遍历就够了。
设置一个“滑窗”,
left 记录最新左边不重复下标。
这时候就要添加一个字符map,相当于一个hashmap。 只不过直接用字符编码做key,字符下标做value。
new int[256]
初始为-1
再申请一个res,记录最大滑窗值
比如acabaa
当遇到第二a时, left = m[a] == 0
res = 2
这时候可以继续往后走,到b res=3
到第三个a时候, left = m[a] ==2
滑窗就从这个a开始了。
这算是一个针对该题的 ”巧妙“ 解法 暂时不知道有没有通用性
public int lengthOfLongestSubstring(String s) {
int[] m = new int[256];
Arrays.fill(m, -1);
int res = 0, left = -1;
for (int i = 0; i < s.length(); ++i) {
left = Math.max(left, m[s.charAt(i)]);
m[s.charAt(i)] = i;
res = Math.max(res, i - left);
}
return res;
}
以上是关于[leetcode]3-Longest Substring Without Repeating Characters的主要内容,如果未能解决你的问题,请参考以下文章
3. 没有重复字母的最长子串 [leetcode 3: Longest Substring Without Repeating Characters]
3. 没有重复字母的最长子串 [leetcode 3: Longest Substring Without Repeating Characters]
leetcode 3. Longest Substring Without Repeating Characters (Python版)
LeetCode - 3 - Longest Substring Without Repeating Characters