美文网首页
Longest String Without Repeating

Longest String Without Repeating

作者: QuentinnYANG | 来源:发表于2018-10-31 09:40 被阅读0次

    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;
    }
    

    相关文章

      网友评论

          本文标题:Longest String Without Repeating

          本文链接:https://www.haomeiwen.com/subject/xzggtqtx.html