题目描述
题目出处:LeetCode 剑指offer 48:最长不含重复字符的子字符串
这道题和LeetCode 3:无重复字符的最长子串相同。
请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。曾经面试农业银行,二面出了这道题。
思路
如果采用暴力的方法,首先一个长度为n的字符串,它的子串有n(n+1)/2个,复杂度为O(n2),判断长度为n的字符串是否有重复字符需要遍历一遍,复杂度为O(n),那么总的时间复杂度为O(n3)。可以使用动态规划。
class Solution {
public int lengthOfLongestSubstring(String s) {
Map<Character, Integer> map = new HashMap<>();
int res = 0;
int temp = 0;
for (int j = 0; j < s.length(); j++) {
int i = -1;
if (map.containsKey(s.charAt(j))) {
i = map.get(s.charAt(j));
}
temp = temp < j-i ? temp + 1 : j - i;
res = Math.max(res, temp);
map.put(s.charAt(j), j);
}
return res;
}
}