【LeetCode】3. Longest Substring Without Repeating Characters

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 a substring, "pwke" is a subsequence and not a substring.

找到不包含重复字母的最长字符串

解题思路:

1.用双指针i,j;其中j往后遍历,thiscount++,当遇到重复的字符时候,j停下

2.用BitMap保存已经遍历过的字符

3.当j停下时候,i往后遍历至重复字符第一次出现的值后面,同时thiscout--

 1 int lengthOfLongestSubstring(char* s) {
 2     int i=0,j=0;
 3     int flag[10]={0};  //创建BitMap
 4     int c;
 5     int count=0,thiscount=0;
 6     while(s[j])
 7     {
 8         c=s[j];
 9         if(!(flag[c>>5]&(1<<(c&0x1f)))) //当此字符不重复时
10         {
11             flag[c>>5]|=(1<<(c&0x1f));   //标记字符
12             thiscount++;
13             if(thiscount>count)
14                 count=thiscount;
15         }
16         else
17         {
18             while(s[i]!=s[j])
19             {
20                 c=s[i];
21                 flag[c>>5]^=(1<<(c&0x1f));  //把重复字符及其第一次出现位置之前的字符从BitMap中删除
22                 thiscount--;
23                 i++;
24             }
25             i++;
26         }
27         j++;
28     }
29     return count;
30 }
原文地址:https://www.cnblogs.com/fcyworld/p/6146523.html