LeetCode 3 Longest Substring Without Repeating Characters(最长不重复子序列)

题目来源:https://leetcode.com/problems/longest-substring-without-repeating-characters/

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

解题思路:

用一个start来记录目前字符串的开头
用exist[MAX]来记录目前字符串中出现过的字母
用pos[MAX]来记录出现过的字符串的字母的位置
 
然后我们往后走一位,然后和exist来比较看这个字母是否已经出现过了。
 
1 如果出现过了,那么我们把start移动到之前那个字母出现的位置的后一位,end往后移动一位
2 如果没有出现过,那么我们就把end往后移动一位
提交代码:
 1 class Solution {
 2 public:
 3     int lengthOfLongestSubstring(string s) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         int locs[256];//保存字符上一次出现的位置
 7         memset(locs, -1, sizeof(locs));
 8 
 9         int idx = -1, max = 0;//idx为当前子串的开始位置-1
10         for (int i = 0; i < s.size(); i++)
11         {
12             if (locs[s[i]] > idx)//如果当前字符出现过,那么当前子串的起始位置为这个字符上一次出现的位置+1
13             {
14                 idx = locs[s[i]];
15             }
16 
17             if (i - idx > max)
18             {
19                 max = i - idx;
20             }
21 
22             locs[s[i]] = i;
23         }
24         return max;
25     }
26 };

其他解题方法:

 1 #include <bits/stdc++.h>
 2 #define MAX 110
 3 
 4 using namespace std;
 5 
 6 int pos[MAX], exist[MAX];
 7 
 8 int main()
 9 {
10     string s;
11     int lens,i,j,start,max_num;
12     while(cin>>s)
13     {
14         lens=s.size();
15         max_num=0,start=0;
16         memset(pos,0,sizeof(pos));
17         memset(exist,0,sizeof(exist));
18         for(i=0;i<lens;i++)
19         {
20             if(exist[s[i]-'a'])
21             {
22                 for(j=start;j<=pos[s[i]-'a'];j++)
23                     exist[s[j]-'a']=0;
24                 start=pos[s[i]-'a']+1;
25                 exist[s[i]-'a']=1;
26                 pos[s[i]-'a']=i;
27             }
28             else
29             {
30                 exist[s[i]-'a']=1;
31                 pos[s[i]-'a']=i;
32                 max_num=max(max_num,i-start+1);
33             }
34         }
35         printf("%d\n",max_num);
36     }
37 }

 

转载于:https://www.cnblogs.com/zpfbuaa/p/5050220.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值