Longest String Without Repeating Characters

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;
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,172评论 0 10
  • 又一阵剧烈的咳嗽,我侧身弯屈身体,手抵着腰,让咳嗽顺畅些。 别人咳嗽是胸口疼,咳嗽时捂胸口。而我咳嗽时腰疼得比胸口...
    稻草人CX阅读 1,778评论 2 1
  • 难忘今宵还在耳边回荡,新年好像就这么匆匆开始了,一眨眼,可能就结束了,假期总是比工作日过得快很多。 热热闹闹的新年...
    九作阅读 2,948评论 0 2

友情链接更多精彩内容