Longest String Without Repeating

2018-10-31  本文已影响0人  QuentinnYANG

Problem Declaration

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.

C++ Solution

//Solution.h
#ifndef CLIONPROJECTS_SOLUTION_H
#define CLIONPROJECTS_SOLUTION_H

#include <string>

class Solution {
public:
    static int lengthOfLongestSubstring(std::string s);
};

#endif //CLIONPROJECTS_SOLUTION_H

//Solution.cpp
#include "Solution.h"
#include <string>
#include <map>

int Solution::lengthOfLongestSubstring(std::string s)
{
    int length = s.length();
    int answer = 0;

    std::map<char, int> map;

    for(int i = 0, j = 0; j < length; j++)
    {
        std::map<char, int>::iterator iter = map.find(s[j]);
        if(map.end() != iter)
        {
            i =  iter->second > i ? iter->second : i;
        }
        answer = answer > (j - i + 1) ? answer : (j - i + 1);
        //Note that insert will not overlap the original value if key already exists.
        //map.insert(std::pair<char, int>(s[j], j + 1));
        map[s[j]] = j + 1;
    }
    return answer;
}

//main.cpp
#include <iostream>
#include "Solution.h"

int main(int argc, char* argv[])
{
    std::string test = "abcadae";
    int a = Solution::lengthOfLongestSubstring(test);
    std::cout << a << std::endl;
    return 0;
}
上一篇下一篇

猜你喜欢

热点阅读