LeetCode刷题系列之Longest Substring Without Repeating Characters

Description

原文:

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.

翻译:

给定一个字符串,找出没有重复字符的最长子字符串的长度。

Solution

class Solution {
public:
int lengthOfLongestSubstring(string s) {
    int ans = 0, left = 0, len = s.length();
    int last[255];
    memset(last, -1, sizeof last);

    for (int i = 0; i < len; ++i) {
        if (last[s[i]] >= left) left = last[s[i]] + 1;
        last[s[i]] = i;
        ans = max(ans, i - left + 1);
    }

    return ans;
}
};

Conclusion

  1. 这个题目的意思理解了很久

  2. 使用memset时候,发现自己对这个函数的理解原来是有问题的,正常是对字符,但是经常会看到针对int数组的初始化:

    int last[255]; memset(last, -1, sizeof last);

    或者

    int last[255]; memset(last, 0, sizeof last);,

    以上的使用方式都是正确的。我刚开始写的时候写成了如下的错误形式:

    int last[255]; memset(last, -1, sizeof(last)/sizeof(int);

    用debug模式,发现last数组并不是说有的都被初始化为-1,后面想了下,memset应该是按照指针类型的字节数初始化,一个int一般是4个字节或者8个字节,如果我写成sizeof(last)/sizeof(int)得到是实际的数组个数,memset做处理就会少初始化了。

你可能感兴趣的:(LeetCode刷题系列之Longest Substring Without Repeating Characters)