最长无重复子串

Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given “abcabcbb”, the answer is “abc”, which the length is 3.

Given “bbbbb”, the answer is “b”, with the length of 1.

Given “pwwkew”, 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.

public class Solution {
    public int lengthOfLongestSubstring(String s)
    {
        int len = s.length(), res = 0;
        Map<Character, Integer> map = new HashMap<>(); // current index of character
        // try to extend the range [i, j]
        for (int j = 0, i = 0; j < len; j++)
        {
            if (map.containsKey(s.charAt(j)))
            {
                i = Math.max(map.get(s.charAt(j))+1, i);
            }
            res = Math.max(res, j - i + 1);
            map.put(s.charAt(j), j);
        }
        return res;
    }
}
求解最长无重复子串是一个经典的算法问题,通常可以利用滑动窗口的思想结合哈希集合(HashSet)来高效解决。以下是详细步骤及思路: ### 核心思想: 1. 使用两个指针 `left` 和 `right` 构成动态变化的窗口 `[left, right]` 来表示当前检查的字符串片段。 2. 借助一个哈希表存储字符及其最后一次出现的位置。 3. 遍历整个字符串时更新窗口大小,并记录最大长度。 #### 具体实现步骤: ```c #include <stdio.h> #include <string.h> int lengthOfLongestSubstring(char *s) { int charIndex[128]; // ASCII 字符集大小 memset(charIndex, -1, sizeof(charIndex)); // 初始化为-1 int left = 0; // 左边界初始化 int maxLength = 0; for (int right = 0; s[right] != '\0'; ++right) { // 右边从头到尾遍历字符串 if (charIndex[s[right]] >= left) { // 如果发现有重复字符并且该字符位置大于等于左边界,则调整左边界 left = charIndex[s[right]] + 1; } charIndex[s[right]] = right; // 更新或插入新字符的最新索引 int currentLength = right - left + 1; // 当前窗口长度 if (currentLength > maxLength) maxLength = currentLength; // 记录最大值 } return maxLength; } // 测试函数 void test() { char str[] = "abcabcbb"; printf("The longest substring without repeating characters is %d\n", lengthOfLongestSubstring(str)); } ``` 此段程序通过维护左右两端不断移动寻找最优结果的方式解决问题,在时间复杂度上达到了 O(n),其中 n 表示输入字符串长度。它保证每个元素最多只会被访问两次——一次由右端点触发、另一次可能因为新的非重复条件改变左端点引起。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值