Longest Substring Without Repeating Characters

来源:互联网 发布:sizeof求数组长度 编辑:程序博客网 时间:2024/06/07 04:45

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be asubstring, "pwke" is a subsequence and not a substring.

本题的要求是找出无重复的最长子字符串的长度.最简单的方法就是穷举所有的子字符串,判断它们是否是无重复的.对于一个子字符串,可以用哈系表记录它的每个字符是否出现过,判断是否重复.该算法的时间复杂度为O(n^3).对于长度为几万的字符串,该算法就不适合.
#include<iostream>#include<string>using namespace std;class Solution {public:int lengthOfLongestSubstring(string s) {int flag[200] = {0};int length=0;for (int i = 0; i < s.length(); ++i)for (int j = i; j < s.length(); ++j) {for (int k =i; k <= j; ++k) {if (flag[s[k]]==1) break;else flag[s[k]]=1;if (k==j && j-i+1>length) length=j-i+1;}for (int z=0; z<200; ++z) flag[z]=0;}return length;    }};

第二种方法是记录下每个字符的下一个相同字符的位置next[i](如果没有相同该字符,则默认为最后一位),再记录下该字符之后第一次出现重复冲突的位置first[i](不一定是与该字符相同).first[i]-i就是无重复字符串的长度.该算法的时间复杂度为O(n).
#include<iostream>#include<string>using namespace std;class Solution {public:        int lengthOfLongestSubstring(string s) {if (s.length()==0) return 0;                int hash[200];for (int i = 0; i < 200; ++i) hash[i]=s.length();int next[s.length()];int first[s.length()+1];first[s.length()]=s.length();                int length=0;                for (int i = s.length()-1; i >= 0; --i) {next[i]=hash[s[i]];hash[s[i]]=i;if (next[i] < first[i+1]) first[i]=next[i];else first[i] =first[i+1];}for (int i = 0; i < s.length(); ++i) {if (first[i]-i>length) length=first[i]-i;}                return length;    }};


原创粉丝点击