Longest Substring Without Repeating Characters

来源:互联网 发布:centos 6.2安装chrome 编辑:程序博客网 时间:2024/05/17 07:43

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)时间复杂度的思路如下:用一个数组pos[256]存储字符首次出现的位置,用cur_len表示当前子串的长度,遍历源字符串时,当前子串长度增加有两种情况:
1. 当前字符没有出现过
2. 当前字符在当前子串中没有出现
当当前字符出现在当前子串中时,也就是出现重复了,将当前子串的长度与最大长度比较,更新最大长度,同时更新当前子串的长度。

class Solution {public:    int lengthOfLongestSubstring(string s) {        if(s.empty() || s == "")            return 0;        int max_len = 1;        int cur_len = 1;        int *pos = new int[256];        memset(pos,-1,sizeof(int) * 256);        int len = s.length();        int pre_pos;        pos[s[0]] = 0;        for(int i = 1; i < len; ++i){            pre_pos = pos[s[i]];            if(pre_pos == -1|| i - cur_len > pre_pos)                cur_len ++;            else{                if(cur_len > max_len)                    max_len = cur_len;                cur_len = i - pre_pos;            }            pos[s[i]] = i;        }        if(cur_len > max_len)            max_len = cur_len;        delete pos;        return max_len;    }};
0 0
原创粉丝点击