LeetCode 3. Longest Substring Without Repeating Characters

来源:互联网 发布:vb杨辉三角形 编辑:程序博客网 时间:2024/05/21 06:26

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.


To solve this problem, I used two pointers and hashmap. I add an example for illustration.


#include <string>#include <iostream>using namespace std;// "abcabcbb" -> "abc"// Two Pointers Methodint lengthOfLongestSubstring(string s) {    if(s.size() <= 1) return s.size();    bool map[256] = {false};    int i = 0;    int j = 0;    int maxLen = 0;    while(i < s.size()) {        if(!map[s[i]]) {            map[s[i]] = true;            i++;        } else {            maxLen = max(maxLen, i - j);            while(s[i] != s[j]) {                map[s[j]] = false;                j++;            }            i++;            j++;        }    }    maxLen = max(maxLen, i - j);    return maxLen;}int main(void) {    string test = "aab";    int len = lengthOfLongestSubstring(test);    cout << len << endl;}


0 0
原创粉丝点击