Leetcode 3. Longest Substring Without Repeating Characters

来源:互联网 发布:淘宝开朗爸的店怎么样 编辑:程序博客网 时间:2024/05/22 05:51

题目: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.

Subscribe to see which companies asked this question.

思路:

首先解释每个数据的意义:
ans为最终的结果,left表示我们最终子串最左边的字母在string s中的位置
last数组表示所检测的字母的上一次出现时在string s中的位置
然后思路就很清晰了
先对last数组赋值,全部置为-1,表示之前都没出现过
然后进行遍历
如果:该字母上一次出现时在left的后面(last[s[i]] >= left),表示该字母已经出现过了,重复了
那么:left就赋值为这个字母上一次出现的位置的下一位
否则:表示该字母就是第一次出现,left不用动,但是这个字母在string s 中就有位置了,得赋值,也就是i
最后:比较ans 和 i - left + 1的大小
然后return 就好


代码:

class Solution {public:    int lengthOfLongestSubstring(string s) {        int ans = 0;        int left = 0;        int last[255];        memset(last, -1, sizeof last);        for (int i = 0; i < s.length(); i++)        {            if (last[s[i]] >= left)            {                left = last[s[i]] + 1;            }            last[s[i]] = i;            ans = max(ans, i - left + 1);        }        return ans;    }};
0 0
原创粉丝点击