Leetcode 3 Longest Substring Without Repeating Characters

来源:互联网 发布:carven淘宝旗舰店 编辑:程序博客网 时间:2024/05/17 09:34

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.

Subscribe to see which companies asked this question

class Solution {public:    int lengthOfLongestSubstring(string s) {       map<char,int> alpha2num;int maxLen = 0, stratIndex=0;for (int i = 0; i < s.size(); ++i){if(alpha2num.count(s[i])) {int loc = alpha2num[s[i]];if(loc+1 > stratIndex) {stratIndex = loc+1;}}alpha2num[s[i]] = i;if(i-stratIndex+1 > maxLen) {maxLen = i-stratIndex+1;}}return maxLen;    }};

#include <iostream>#include <string>#include <cstdio>#include <map>using namespace std;class Solution {public:int lengthOfLongestSubstring(string s) {map<char,int> alpha2num;int maxLen = 0, stratIndex=0;for (int i = 0; i < s.size(); ++i){if(alpha2num.count(s[i])) {int loc = alpha2num[s[i]];if(loc+1 > stratIndex) {stratIndex = loc+1;}alpha2num[s[i]] = i;if(i-stratIndex+1 > maxLen) {maxLen = i-stratIndex+1;}} else {alpha2num[s[i]]=i;if(maxLen < i+1-stratIndex)maxLen = i+1-stratIndex;}}return maxLen;}};int main() {Solution *ss = new Solution();string s;cin >> s;int ans = ss->lengthOfLongestSubstring(s);cout << ans << endl;}


0 0
原创粉丝点击