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.
从头开始扫描,利用i,j记录当前未重复的子字符串的起点和终点,用数组flag和loc分别记录字符串是否出现以及首次出现的位置,当碰到第一个重复的字符时,记录下当前的子字符串的长度,并将字符串的起点i设置为当前重复字符的位置,j不变,将截取的部分字符串中出现的字符状态设为false,如此继续下去,只需扫描一遍字符串即可找到符合题目要求的子字符串,算法的时间复杂度为O(N)
算法实现:
class Solution { public: const static int R = 256; int lengthOfLongestSubstring(string s) { bool flag[R]; int res = 0; int loc[R]; for(int m=0; m<R; m++) flag[m] = false; int j=0; int i=0; int n = s.length(); int count = 0; while(j<n && i<n) { if(flag[s[j]]) { count = j-i; for(int m=i; m<loc[s[j]]; m++) flag[s[m]] = false; i = loc[s[j]]+1; loc[s[j]] = j; if(count > res) res = count; } else { flag[s[j]] = true; loc[s[j]] = j; } j++; } if(j == n && j-i > res) res = j-i; return res; } };
LeetCode---Longest Substring Without Repeating Characters
原文地址:http://blog.csdn.net/shaya118/article/details/42501469