欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > > 文章正文

Longest Substring Without Repeating Characters,longestrepeating

来源: javaer 分享于  点击 8877 次 点评:225

Longest Substring Without Repeating Characters,longestrepeating


Longest Substring Without Repeating Characters

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.

题意在原串中找到最长的每个字母最多出现一次的字符串

用一个sign[256]来记录出现过的字符位置,偷懒点用265可以处理一个ASCII表。
遇到没有出现过的字符,将sign对应位置标记-1。
遇到出现过的字符,出现该字符上次出现位置前面截断(即赋值为-1),调整长度。

#include<iostream>
#include <algorithm>
#include<cstring>
using namespace std;
class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int start = 0;
        int movep = 0;
        int sign[256];
        int mmax = 0;
        int templen = 0;
        int curStart = 0;
        int lastSi = 0;
        memset(sign,-1,sizeof(sign));   //注意mem第三个参数,类型是size_t
        for(;movep<s.size();movep++)
        {
            char si = s[movep];
            lastSi = sign[si];
            if( sign[si] == -1)
            {
                templen++;
                sign[si] = movep;
            }
            else
            {
                //删除前面重复的,重新调整长度
                curStart = movep - templen;
                for(int j = curStart; j < lastSi; ++j) {
                    sign[s[j]] = -1;
                }
                templen = movep - lastSi;
                sign[si] = movep;
            }
            mmax = max(mmax,templen);
        }

        return mmax;
    }
};


相关文章

    暂无相关文章

用户点评