leetcode: Longest Substring Without Repeating Characters

来源:互联网 发布:java静态变量初始化 编辑:程序博客网 时间:2024/05/21 06:16

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.

用一个数组记录每个字符出现的位置,遇到重复的,从上一个出现位置继续O(n)

class Solution {public:    int lengthOfLongestSubstring(string s) {        int used[256];        memset( used, 0, sizeof(used));        int tmp = 0, maximum = 0;        for( int i = 0; i < s.size(); ++i){                if( used[s[i]] > 0){                    i = used[s[i]] - 1;                    memset( used, 0, sizeof( used));//这里注意不要大意                    maximum = max( maximum, tmp);                    tmp = 0;                }                else{                    used[s[i]] = i + 1;                    ++tmp;                }        }        return max( maximum, tmp);//别忘了最后一次    }};


0 0
原创粉丝点击