您的位置:首页 > 编程语言 > C语言/C++

【LeetCode】3.Longest Substring Without RepeatingCharacters寻找最大string

2017-08-01 18:41 363 查看
Longest Substring Without RepeatingCharacters
Givena 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"
 isa subsequenceandnot
a substring.

//分析题意,很明显,让你找出一串英文字符串的中的最大不重复子字符串。最简单的就是for(){for(){}}??????暴力求解

这里我们分析,如果我们用两个指针,一个作为子字符串的开始i,一个作为结束j。我们移动j。那么问题来了,我们如何判断他们重复不重复呢?

我们都知道,每一个英文字母都有一个int类型与之对应,比如char a=’a’;

那么存在int b=a; b的数值为65.

So,每个字母都有一个意义对应的数字,而且在256以内,所以我们用一个bool型数组来表示一个字母是否被访问过。

class Solution {

public:

intlengthOfLongestSubstring(string s) {

//该函数的返回值是一个int类型的数据,也就是最长的字符串

      int n=s.length();

      int i=0,j=0;

       int max_length=0;

       int cur_length=0;

       bool exits[256]={false};

//定义上文提到的字母访问标识

       while(j<n){

if(!exits[s[j]]){

//如果该字母没有被访问过

                exits[s[j]]=true;

                j++;

//将其标记为访问过true

}else{

//如果被访问过,则将其循环寻找之前相同的字母,并将之前相同字母i之前的记为false(未被访问过标记),然后从之前相同字母i开始,重新寻找不重复字母长度。直到j=n

                while(s[i]!=s[j]){

                    exits[s[i]]=false;

                    i++;

           }

                i++;

                j++;}

                cur_length=j-i;

               max_length=max_length>cur_length?max_length:cur_length;

    //最大长度

       }

           

       return max_length;

    }

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐