Longest Substring Without Repeating Characters(medium)

来源:互联网 发布:电脑管家mac版 编辑:程序博客网 时间:2024/05/01 04:41

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

这题首先要解决的问题是如何判断字符串中的某个字符是否在之前的位置出现过,我一开始想到的方法是用一个大小为300的int类型数组x(我不知道ASCII一共有多少个字符,好像200多个,索性用300保险一点)来对应每个ASCII中的字符,初始化全部为0,当检测到某一个字符(假设为’a’)时就把这个x[‘a’]赋值1,这样对于输入的字符串逐个检测的时候就能知道当前字符是否曾经出现。
接着是如何找到最大子串,假设从目标字符串从头开始组成子串,当检测到当前字符(假设为第i位)已经出现过的时候(假设出现在第k位),显然从首位到当前字符的前一位就是当前的最大子串(0,i-1),此时要做的就是将子串的首位置为第i位的字符第一次出现的位置的后一位,也就是k+1的位置,因为任何以在(0,k)内为起点的子串到i的时候必然有重复而且也比(0,i-1)子串要短。接着就是逐一增加当前检测位,重复以上过程找阶段性最长的子串,与已经找到的最长子串比较,直到目标子串的最后一位。
为了实现上述过程我还增加了一个与x同样的数组y,记录字符出项的位置,值得注意的是要判断当前字符是否已经出现不单单要看x,还要看y中对应的位置是否在当前子串的头的右边,因为子串的头一直在变化,只有在右边出现过才算出现在当前子串中。
我的代码:

class Solution {public:    int lengthOfLongestSubstring(string s) {        int x[300] = {};        int y[300] = {};        int outcome = 0;        int curmax = 0;        int curhead = 0;        for (int i = 0; i < s.size(); i++) {            if (x[s[i]] == 0) {                x[s[i]] = 1;                y[s[i]] = i;                curmax++;                continue;            }            else {                if (y[s[i]] < curhead) {                    y[s[i]] = i;                    curmax++;                    continue;                }                else {                    if (curmax > outcome)                        outcome = curmax;                    curmax = i - y[s[i]];                    curhead = y[s[i]] + 1;                    y[s[i]] = i;                    continue;                }            }            if (curmax > outcome)                outcome = curmax;                   //这个主要针对从头到尾都是不一样的字符或者只有一个字符的情况        }        return outcome;    }};
0 0
原创粉丝点击