面试题48:最长不含重复字符的子字符串
题目:请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。假设字符串中只包含’a’~'z’的字符。例如,在字符串"arabcacfr"中,最长的不含重复字符的子字符串是"acfr",长度为4。
思路1:
- 创建一个dp数组,dp[i]表示以第 i 个字符结尾的最长连续字符串的长度。
- 创建一个 temp 数组,记录着以第 i 个字符结尾的最长连续字符串。
- 假设遍历到第 i 个字符 ch,如果 ch 出现在 temp 中,则 temp 为ch出现的位置的下一个字符到当前位置。dp[i] 为 temp 的长度。
- 最后返回 dp 数组中的最大值。(当然也可以用一个变量来记录最大值)
代码实现:
public static int solve(String s) {
if(s == null || s.length() == 0) return 0;
int result = 0;
String temp = "";
int[] dp = new int[s.length()];
for(int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if(i == 0) dp[i] = 1;
else {
int pos = temp.indexOf(ch);
if(pos >= 0) {
dp[i] = temp.length() - pos;
temp = temp.substring(pos+1, temp.length());
}
else dp[i] = dp[i-1] + 1;
}
if(dp[i] > result) result = dp[i];
temp += ch;
}
return result;
}
思路2:
- 其实发现,不需要dp数组,只需要比较result与temp的长度,如果temp的长度大于result,则更新result,否则result不变。这样可以进一步缩小空间。
代码实现:
public static int solve2(String s) {
if(s == null || s.length() == 0) return 0;
int result = 0;
String temp = "";
for(int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
temp += ch;
if(temp.indexOf(ch) != temp.length() - 1) temp = temp.substring(temp.indexOf(ch)+1, temp.length());
if(temp.length() > result) result = temp.length();
}
return result;
}
思路3:
- 每次都要看 temp 字符串是否含有当前字符,每次都要进行扫描,可以使用hashMap来缩减这一块的时间。
- 使用hashMap<Character, Integer>来记录每个字符最后一次出现的索引。然后用 i - pos 来判断这个字符是否出现在了以 i-1 为结尾的最长连续字符串中。
代码实现:
public static int solve3(String s) {
int result = 0;
if(s == null || s.length() == 0) return result;
Map<Character, Integer> map = new HashMap<>();
int count = 0;
for(int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if(map.containsKey(ch) && i - map.get(ch) <= count) count = i - map.get(ch);
else count++;
if(count > result) result = count;
map.put(ch, i);
}
return result;
}