算法设计与分析课作业【week1】 Longest Substring Without Repeating Characters

本文介绍了一种高效求解最长无重复字符子字符串的方法,通过使用vector容器追踪字符,确保仅需遍历字符串一次即可得出结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

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

Example 1:

Input: "abcabcbb"
Output: 3 
Explanation: The answer is "abc", which the length is 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.

题目描述很简单,找出字符串中最长的没有重复字符的子字符串,输出该串的长度。

解决方法:利用vector容器,将字符依次放入vector容器中,一旦出现重复的字符,确定该子字符串长度后,便将容器内的字符从头到该重复字符的位置的所有字符删除,继续判断之后的字符。这样只需要遍历一次字符串即可。

代码如下:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        vector<char> vec;
        int max = 0;
        for (int i = 0; i < s.length(); ++i) {
                int pos = findChar(vec, s[i]);
                if (pos != -1) {
                    if (vec.size() > max) max = vec.size();
                    vec.erase(vec.begin(), vec.begin() + pos + 1);
                }
                vec.push_back(s[i]);
            }
        return vec.size() > max ? vec.size() : max;
    }
    
    int findChar(vector<char> & vec, char newchar) {
        for (int i = 0; i < vec.size(); ++i) {
            if (vec[i] == newchar)
                return i;
        }
        return -1;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值