首页 > 代码库 > [leetcode]3. Longest Substring Without Repeating Characters

[leetcode]3. Longest Substring Without Repeating Characters

题目:

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.

 

题目的意思是给一串字符串,要求找出里面最长的不重复字串,还给了个提示,说对于pwwkew,wke是字串,pwke不是,是子序列,因为pwke不是黏在一起的。

这题很简单,直接哈希标记下,从前扫到后,踩到重复的字符就停下来比对一下就行了。

//
// Created by x on 2017/6/29.
//
#include<iostream>
#include<string>
#include<string.h>
using namespace std;
int lengthOfLongestSubstring(string s) {
    int begin=0;
    bool chars[256];
    string longsubstr="";
    while(begin<s.size()){
        memset(chars,false,sizeof(chars));
        string tempsubstr="";
        for(int i = begin;i<s.size();i++){
            if(chars[(int)s[i]]==false){
                tempsubstr += s[i];
                chars[(int)s[i]]=true;
            }
            else{
                break;
            }
        }
        if(tempsubstr.size()>longsubstr.size()){
            longsubstr=tempsubstr;
        }
        begin++;
    }
    return longsubstr.size();
}
int main(){
    string s;
    while(cin>>s)
        cout<<lengthOfLongestSubstring(s);
}

 

[leetcode]3. Longest Substring Without Repeating Characters