LeetCode OJ(3.Longest Substring Without Repeating Characters)

来源:互联网 发布:刷新快捷键 mac 编辑:程序博客网 时间:2024/06/06 05:55

从今天开始不要追求题目的数量了,学会一题多解,开阔思路,熟练写法,题目是做不完的,关键是做得有质量才能提高编程能力。
题目描述:
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.
思路:可以采用hash算法,字符的二进制值映射到一个locs[256]数组中,令其值为-1,在值不为-1的索引处也恰好存储该字符的索引。注意到,从第一个字符开始遍历,若遍历到有与第一个字符相同的字符,则之前的都不可能是满足要求的substring,将起始位置设为当前位置+1,代码如下:

class Solution {public:    int lengthOfLongestSubstring(string s) {        int locs[256];        memset(locs, -1, sizeof(locs));        int start = -1, max = 0;//start为当前子串的开始位置-1        for (int i = 0; i < s.size(); i++)        {            if (locs[s[i]] >start)            {                start = locs[s[i]];            }            if (i - start > max)            {                max = i - start;            }            locs[s[i]] = i;        }        return max;    }};

还有另一种写法,不使用locs[256]那么大的数组来存储各个字符的二进制码,转换成字符来写,不过解法还是一样的。这种解法对于除字母之外的测试用例通不过,原因就在于(-‘a’)操作。

class Solution {public:    int lengthOfLongestSubstring(string s) {        int max = 0, start = 0;        bool showed[26];        int position[26];        for (int i = 0; i < 26; i++) {            showed[i] = false;            position[i] = 0;        }        for (int i = 0; i<s.size(); i++)        {            if (showed[s[i] - 'a'])            {                start = position[s[i] - 'a'] + 1;                showed[s[i] - 'a'] = true;                position[s[i] - 'a'] = i;            }            else            {                position[s[i] - 'a'] = i;                showed[s[i] - 'a'] = true;                max = max > (i - start + 1) ? max : (i - start + 1);            }        }        return max;    }};
0 0
原创粉丝点击