欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Longest Substring Without Repeating Characters

程序员文章站 2023-11-04 11:57:22
Longest Substring Without Repeating Characters ......

3.longest substring without repeating characters

given a string, find the length of the longest substring without repeating characters.

example 1:

input: "abcabcbb"
output: 3 
explanation: the answer is "abc", with the length of 3. 

example 2:

input: "bbbbb"
output: 1
explanation: the answer is "b", with the length of 1.

example 3:

input: "pwwkew"
output: 3
explanation: 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.

code

//
//  main.cpp
//  最长无重复子串
//
//  created by mac on 2019/7/16.
//  copyright © 2019 mac. all rights reserved.
//

#include <iostream>

#include <string.h>

#include <algorithm>

#include <vector>

using namespace std;

class solution {
public:
    int lengthoflongestsubstring(string s) {
        string tmp="";
        vector<int> max = {0};
        for (int i=0; i<s.size(); ++i) {
            if (tmp.find(s[i])==18446744073709551615 && !s.empty()) {
                tmp.append(1,s[i]);
                if(i==s.size()-1){
                    max.push_back(tmp.size());
                }
                
            }else{
                max.push_back(tmp.size());
                i=i-tmp.size();
                tmp="";
            }
            
        }
        return *max_element(max.begin(),max.end());
    }
};

int main(int argc, const char * argv[]) {
    
    string a="ghhvvgyjkkkhgfrtyjjhhhhuuikikjhytyyuik";
    string b="";
    if (a==b) {
        cout<<"相等"<<endl;
    }
    //cout<<a[1]<<endl;
   // cout<<a.size()<<endl;
    //18446744073709551615
    //cout<<a.find("k")<<endl;
    if (-1!=18446744073709551615) {
        cout<<"相等了"<<endl;
    }
    
    solution so;
    cout<<so.lengthoflongestsubstring(a)<<endl;
    
    cout<<a.empty()<<endl;

    return 0;
}

运行结果

8
0
program ended with exit code: 0

参考文献