leetcode__Longest Substring Without Repeating Characters

来源:互联网 发布:恐怖黎明物品数据官网 编辑:程序博客网 时间:2024/06/13 03:42

The Question is:

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.


Analyse:

解决这道题的时候,我采用的方法是,第一个for循环遍历字符串中的元素,如果遍历到一个元素,前面有与它一样的元素,那么就跳到前面那个元素的后面一个元素重新开始统计,例如遍历”dvdsw”,遍历到第2个d的时候,发现前面有个重复的d,那么记录此时的长度,从前面一个d的后面一个元素v,重新开始统计,比较每次统计的结果取最大值,第二个for循环就是查找重复的值,直到所有都查完了,就退出while循环。


The Answer is:

#include<iostream>#include<string>using namespace std;int lengthOfLongestSubstring(string s);int main(){    string x = "dvdsw";    cout<<lengthOfLongestSubstring(x);    return 0;}int lengthOfLongestSubstring(string s){    int count,record = 0,index = 0;    int i = 0,j;    bool flag = false;//标志位,查到如果有重复的,就令flag = true    while(index < s.size()&&i< s.size())//遍历结束    {        count = 0;        flag = false;//每次开始都要初始化,重新统计字符        for(i = index; i<s.length(); i++)        {            for(j = index; j<i; j++)            {                if(s[i] == s[j])                {                    count = 0;                    flag = true;                    index = j+1;//前面一个相同元素的后面一个字符                    break;//退出循环重新开始                }            }            count++;            record = count>record?count:record;//每次统计取最大            if(flag)break;//退出第二层循环重新开始        }    }    return record;}