Fork me on GitHub

[leetcode-3-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.

思路:

  • 从前到后扫描字符串,并将字符存入map中。
  • 时刻查看当前字符是否已经存在map中了,不存在就继续。
  • 如果已经存在则从那个字符处下一个作为子串起点,继续向前扫描。
int lengthOfLongestSubstring(string s)
    {
        int size = s.size();
        if (size <= 1)return size;
        unordered_map<char,int> table;//用来记录字母与对应的下标值
        int length = 0;
        int result = 0;
        int tempIndex = 0;
        int temp = 0;
        for (int i = 0; i < size; i++)
        {
            if (table.count(s[i])>0)//说明map里面有
            {
                result = max(result, length);
                length = i - table[s[i]]-1;
                temp = table[s[i]];
                for (int j = tempIndex; j <= temp; j++)
                {
                    table.erase(s[j]);//将这个重复元素之前所有去掉        
                }
                tempIndex = temp + 1;//保存新的起点下标                
            }
            table[s[i]] = i;//记录下标索引值
            length++;            
        }
        result = max(result, length);
        return result;
    }

 看到一个更牛的,即简介且高效:

用一个向量来统计字符出现次数。

int lengthOfLongestSubstring(string s) {
        vector<int> dict(256, -1);
        int maxLen = 0, start = -1;
        for (int i = 0; i != s.length(); i++) {
            if (dict[s[i]] > start)
                start = dict[s[i]];
            dict[s[i]] = i;
            maxLen = max(maxLen, i - start);
        }
        return maxLen;
    }

参考:

https://discuss.leetcode.com/topic/24739/c-code-in-9-lines

posted @ 2017-03-16 16:53  hellowOOOrld  阅读(147)  评论(0编辑  收藏  举报