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

题目

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;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_36332464/article/details/82559666