【leetcode】Longest Substring Without Repeating Characters

来源:互联网 发布:python课程推荐 编辑:程序博客网 时间:2024/05/29 18:10

题目:

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.

解析:寻找字符串中没有字符重复的最长子串比如“abcabcbb”中的最长子串是“abc”,“bbbbb”中的最长子串是"b"。

用DP和Hash的思想做这道题,建立一个大小为26的数组,记录a~z每个字符最新出现的字符串位置。用变量count记录包含当前字符的子串已有的最长长度。遍历字符串的每一个字符,如果某个字符对应hash数组中的值在count范围内,更新count的值。如果某个字符对应hash数组中的值在count范围外,更新hash的值并且count++,还要判断是否要更新最长子串长度max。时间复杂度为O(N),C++ AC代码如下:

int lengthOfLongestSubstring(string s) {                 int hash[26];                 int i;                 for (i = 0; i < 26; i++){                     hash[i] = -1; //所有字母的初始位置都为-1,注意不能为0                 }                 int count = 0,max=0;                 for (i = 0; i < s .length(); i++){                     int temp = s [i] - 'a';                     if (hash[temp]<(i - count)){                         count++;                         if (count>max){                             max = count;                         }                      }else{                         count = i - hash[temp];                           }                      hash[temp] = i;                }                 if (count>max){                      max = count;                }                 return max;}




1 0
原创粉丝点击