003 Longest Substring Without Repeating Characters [Leetcode]

来源:互联网 发布:mac如何完全卸载软件 编辑:程序博客网 时间:2024/05/21 09:21

题目内容:

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.

解题思路:
顺序遍历,使用hash表记录已经读到过的字母。
由于ASCII码足够表示所有字符了,使用一个长度为128的数组记录出现的下标即可。
每次读到重复的数字时,不重复字符串的起始位置就变为hash表中记录的下标的后一位,并更新最长字符串长度和hash表中记录的当前字母的下标。
时间复杂度为O(n)。

代码:

class Solution{public:    int lengthOfLongestSubstring(string s)    {        if(s == "")            return 0;        int l = 0, r = 0, maxl = 0;        unsigned char cset[128];        memset(cset, 0, 128*sizeof(unsigned char));        while(r < s.size())        {            if(cset[s[r]] == 0)                cset[s[r]] = 1;            else            {                maxl = max(maxl, r - l);                while(s[r] != s[l])                {                    cset[s[l]] = 0;                    ++ l;                }                ++ l;            }            ++ r;        }        maxl = max(maxl, r - l);        return maxl;    }};
0 0
原创粉丝点击