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.
mistakes I made:1. forget record start point. I reset longest to 0 after encountering a repeated char, which is wrong. It should start from the next char following the first char of two repeated chars.
- class Solution {
- public:
- int lengthOfLongestSubstring(string s) {
- bool d[256] = { false };
- int max_len = 0;
- int start = 0;
- for(int i=0; i<s.size(); i++) {
- char c = s[i];
- if(!d[c]) {
- d[c] = true;
- max_len = max(max_len, i-start+1);
- } else {
- while(s[start] != c) {
- d[s[start]] = false;
- ++start;
- }
- ++start;
- }
- }
- return max_len;
- }
- };
- class Solution {
- public:
- int lengthOfLongestSubstring(string s) {
- // Start typing your C/C++ solution below
- // DO NOT write int main() function
- if( s.size() == 0) return 0;
- #define MAX_LEN 256
- char flag[MAX_LEN];
- reset(flag, MAX_LEN);
- int max = 0;
- int longest = 0;
- int start = 0;
- for(int i=0; i<s.size(); i++) {
- if( flag[ s[i] ] == -1 ){
- longest++;
- } else {
- max = max < longest ? longest : max;
- for(int j=start; j<i; j++){
- flag[ s[j] ] = -1;
- if( s[j] == s[i] ) {
- start = j + 1;
- break;
- }
- }
- longest = i - start + 1;
- }
- flag[ s[i] ] = 1;
- }
- max = max < longest ? longest : max;
- return max;
- }
- private:
- void reset(char a[], int n){
- for(int i=0; i<n; i++) {
- a[i] = -1;
- }
- }
- };
- public class Solution {
- public int lengthOfLongestSubstring(String s) {
- // Start typing your Java solution below
- // DO NOT write main() function
- int max = Integer.MIN_VALUE;
- int start = 0;
- HashMap<Character,Integer> map = new HashMap<Character, Integer>();
- for(int i=0; i<s.length(); i++) {
- char c = s.charAt(i);
- if( map.containsKey(c)){
- for(int j=start;j<i;j++) {
- if(s.charAt(j)==c) break;
- map.remove(s.charAt(j));
- }
- start = map.get(c)+1;
- map.put(c,i);
- } else {
- map.put(c,i);
- if( i-start+1 > max ) max = i-start+1;
- }
- }
- return max;
- }
- }
- class Solution {
- public:
- int lengthOfLongestSubstring(string s) {
- // Start typing your C/C++ solution below
- // DO NOT write int main() function
- unordered_set<char> myset;
- int sz = s.size();
- int cur = 0;
- int max = 0;
- int start = 0;
- for(int i=0; i<sz; i++) {
- char c = s[i];
- if( myset.find(c) == myset.end() ) {
- myset.insert(c);
- cur++;
- max = max>cur ? max : cur;
- } else {
- int j=start;
- while( s[j]!=c) {
- myset.erase( s[j] );
- ++j;
- }
- start = j+1;
- cur = i-start+1;
- }
- }
- return max;
- }
- };