码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode]3. Longest Substring Without Repeating Characters

时间:2017-06-29 22:36:58      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:意思   stream   using   cin   namespace   include   str   example   find   

题目:

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

标签:意思   stream   using   cin   namespace   include   str   example   find   

原文地址:http://www.cnblogs.com/fsh01/p/7096303.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!