Given a string, find the longest substring that contains only two unique characters. For example, given "abcbbbbcccbdddadacb", the longest substring that contains k unique character is "bcbbbbcccb". 分析: 用hashmap记录每个character从start到当前位置出现的次数,如果第k + 1个character出现, 更新...
Given a string you need to print the size of the longest possible substring that has exactly k unique characters. If there is no possible substring print -1. Example For the string aabacbebebe and k = 3 the substring will be cbebebe with length 7. Input: The first line of input contai...
Given a string, find the longest substring that contains only two unique characters. For example, given "abcbbbbcccbdddadacb", the longest substring that contains k unique character is "bcbbbbcccb". 分析: 用hashmap记录每个character从start到当前位置出现的次数,如果第k + 1个character出现, 更新ma...
解法一:枚举出字符串的所有子串,去掉有重复字符的那部分,最后找出其中长度最长的那个。最笨的办法,时间复杂度O(n^4)。 intmax_unique_substring1(char*str) {intmaxlen =0;intbegin =0;intn =strlen(str);for(inti=0; i<n; ++i)for(intj=1; j<n; ++j) {intflag =0;for(intm=i; m<=j; ++...
Given a string, find the length of the longest possible substring in it that has exactly K distinct characters. If there is no possible substring then print -1. You can assume that K is less than or equal to the length of the given string.
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. ...
classSolution{publicintlengthOfLongestSubstring(Strings){intans=0;for(inti=0;i<s.length();i++){for(intj=i;j<=s.length();j++){if(isUnique(s,i,j)){ans=Math.max(j-i,ans);}}}returnans;}publicbooleanisUnique(Strings,inti,intj){Set<Character>chSets=newHashSet<>();for(intz=i;z<...
We also need a way to check whether this window has repeating letters - hash map is a better way, but how to construct the hash map and how this map functions? Solutions: When we slide the window, the hash map is constructed with " key of unique letter " and " value of number " ...
Check all the substring one by one to see if it has no duplicate character. Algorithm Suppose we have a functionboolean allUnique(String substring)which will return true if the characters in the substring are all unique, otherwise false. We can iterate through all the possible substrings of ...
public int longestSubstring(String s, int k) { int ans = 0; int uniqueCount = 0; boolean[] exist = new boolean[26]; for (char c : s.toCharArray()) { if (!exist[c - 'a']) { exist[c - 'a'] = true; uniqueCount++; ...