剑指offer之面试题48:最长不含重复字符的子字符串

面试题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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值