Title 5: no repeat of the longest character substring
Given a string, you find out which does not contain a repeated character longest substring length.
Example 1:
输入: "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其
长度为 3。
Example 2:
输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b"
,所以其长度为 1。
Example 3:
输入: "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke"
,所以其长度为 3。
请注意,你的答案必须是 子串 的长度,"pwke"
是一个子序列,不是子串。
方法一:
@ Idea: all elements of the control zone is not repeated, using a hash table to determine. When emptying each iteration // hash table class Solution { public : int lengthOfLongestSubstring ( String S) { int len = s.size (); int HashMap [ 256 ] = { 0 }; int In Flag = 0 ; int Current = 0 ; int Result = Current; int I = 0 ; for (I = 0 ; I <len; I ++ ) { IF(HashMap [S [I]] =! 0 ) { // this sub-string duplication Current = I- In Flag; IF (Result < Current) Result = Current; // clears the hash table for (; In Flag <I; In Flag ++ ) { IF (S [In Flag] =! S [I]) HashMap [S [In Flag]] = 0 ; the else BREAK ; } HashMap [S [I]] = . 1 ; In Flag++ ; } the else { HashMap [S [I]] = . 1 ; // set to 0 } } // process without overlap. I- = Current In Flag; IF (Result < Current) Result = Current; return Result; } };
Method Two:
// Method two: sliding window is advanced my approach. Using hash tables to store the position of the last character string appears int lengthOfLongestSubstring ( String S) { Vector < int > hash ( 256 , - . 1 ); int left = - . 1 ; int ANS = 0 ; for ( int I = 0 ; I <s.size (); ++ I) { IF (the hash [S [I]]> left) { left = the hash [S [I]]; } ANS = max (ANS, I- left); the hash [S [i]]= i; } return ans; }
387 title
The first string a unique character
Given a string, find its first non-repeating characters, and returns its index. If not, it returns -1.
Case:
s = "leetcode"
返回 0.
s = "loveleetcode",
返回 2.
题解:
题解,使用hash表对字符出现的个数进行统计,之后再次遍历字符串查找hash表即可。注意出现次数问题的都可以用这个思路来求解!
// @lc code=start class Solution { public: int firstUniqChar(string s) { int len = s.size(); int result = 0; int hashmap[256] = {0}; for(int i=0;i<len;i++) { hashmap[s[i]]++; } for(int i=0;i<len;i++) { if(HashMap [S [I]] == . 1 ) return I; } return - . 1 ; } }; // do not traverse the hash table, then traverse a string like! ! !