《剑指offer》48--最长不含重复字符的子字符串[C++]

NowCoder

题目描述

输入一个字符串(只包含 a~z 的字符),求其最长不含重复字符的子字符串的长度。例如对于 arabcacfr,最长不含重复字符的子字符串为 acfr,长度为 4。

Example 1:

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

解题思路

动态规划+hash数组

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        if(!s.length()) return 0;
        vector index(256,0);
        int maxLen = 0, n = s.length();
        for (int j = 0, i = 0; j < n; j++) {
            i = max(index[s[j]],i);
            maxLen = max(maxLen, j - i + 1);
            index[s[j]] = j + 1; // must +1 (j = 0)
        }
        return maxLen;
    }
};

 

你可能感兴趣的:(C++)