[LeetCode 3] Longest Substring Without Repeating Characters

https://leetcode.com/problems/longest-substring-without-repeating-characters/

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

比较low的方法是直接暴力,时间复杂度是o(n2),但是仔细观察一下,就会发现可以优化。

例如,"abcdebrt" ,i 指针首先在字符串的起始位置当我们发现第二个 b 时 j 指针到索引为6的位置,这个时候计算一下 maxLength 为5(j - i),那么第二次遍历的时候 i 指针可以直接跳到 c 的位置, j 指针继续往前走,从 i 往后算如果再遇到重复,就更新 maxLength。这样的话,只遍历了字符串一遍(j 指针),时间复杂度降为o(n),太high了,代码如下:

/**
 * 两种情况下需要更新maxLength
 * 1. 发现重复的character
 * 2. 到了最后一个character(且最后一个character与之前的没有重复)
 */


class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        vector<int> hashmap(256, -1);
        int i = 0;
        int maxLength = 0;
        for (int j = 0; j < s.size(); j++) {
            // s[j] 出现
            if (hashmap[s[j]] >= i) {
                maxLength = max(maxLength, j - i);
                i = hashmap[s[j]] + 1;
            } else if (j == s.size() - 1) { //如果有重复,就不用判断最后一个了
                maxLength = max(maxLength, j - i + 1);
            }
            
            hashmap[s[j]] = j;
        }
        return maxLength;
    }
};
posted @ 2015-05-10 21:57  Acjx  阅读(249)  评论(0编辑  收藏  举报