C实现 LeetCode->Longest Substring Without Repeating Characters

来源:互联网 发布:哪个淘宝u站返最多 编辑:程序博客网 时间:2024/05/14 18:57

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.


求一个字符串的 最长不重复子字符串的 长度










////  LongestSubstringWithoutRepeatingCharacters.c//  Algorithms////  Created by TTc on 15/6/5.//  Copyright (c) 2015年 TTc. All rights reserved.//#include "LongestSubstringWithoutRepeatingCharacters.h"#include <string.h>#include <stdlib.h>#include <stdbool.h>//O(2n) = O(n)/** *  新思路: 贪心法,从头扫描到尾O(n)搞定  字符串的很多问题都可以用一个256的map来加速,很方便。  用一个map[256]来记录出现过的字符位置。 遇到没有出现过的字符,将map对应位置标记,并且子串长度+1; 遇到出现过的字符,将子串(自上一次出现该字符位置前面的截断),对这部分截断的字符, 标记map为notFound,重新计算子串长度。  当然,如果已知字符集是a-z + A-Z的话,可以减小map的大小。我这里是偷个懒直接开256。 map[si]是s[i]这个字符在s中的出现位置(上一次出现),如果map[si] == NotFound,说明这个字符s[i]还没有出现过。  复杂度: 我们关注的字串前端是从0走到n-1,后端总是递增,所以最差情况下就是2n,O(2n) = O(n) * */intlengthOfLongestSubstring(char* s) {    int map[256];    int maxlen = 0;    const int notfound = -1;    for (int i =0; i<256; ++i) {        map[i] = notfound;    }    int len = 0;//子串长度    for (int i=0;s[i]; i++) {        //    for (int i=0; i<strlen(s); i++) {        char si = s[i];        int last_s = map[si]; //map中 该字符上一次出现的位置                if(last_s == notfound){            ++len;    // 子串长度+1            map[si] = i; //记录下标            if(maxlen < len)                maxlen = len;        }else{            //如果该字符已经出现过则将子串(排除重复字符的子串)(自上一次出现该字符位置前面的截断),对这部分截断的字符,            //标记map为notFound,重新计算子串长度。            int curStart = i - len;            for (int j = curStart; j < last_s; ++j) {                map[s[j]] = notfound;            }            //            curStart = last_s + 1;            //            len = i- curStart + 1;            len =  i - last_s;            map[si] = i;        }    }    return maxlen;}voidtest_longestSubString(){    char ss[15] = "abacasdsds";    int max = lengthOfLongestSubstring(ss);        printf("max===%d \n",max);}


0 0
原创粉丝点击