leetcode-【中等题】3. Longest Substring Without Repeating Characters

本文探讨LeetCode上一道经典题目:寻找给定字符串中最长的无重复字符子串。通过详细解析算法思路,分享了一种高效求解方法,并附上了C++实现代码。

题目:

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.

链接https://leetcode.com/problems/longest-substring-without-repeating-characters/

答案:

参考了这个链接后才明白解题思路,然后依据自己的理解写了代码。

大致思路是:从当前字符开始,往前看,没有出现过重复字符的字符串

代码:

 1 #define MAX_LETTER_NUM 255
 2 class Solution {
 3 public:
 4     int lengthOfLongestSubstring(string s) {
 5         if(s.empty())
 6         {
 7             return 0;
 8         }
 9         
10         bool exist[MAX_LETTER_NUM];
11         int position[MAX_LETTER_NUM];
12         int index,rangeIndex;
13         int maxLen = 0;
14         int start = 0;
15         
16         for(index = 0; index < MAX_LETTER_NUM; ++ index)
17         {
18             exist[index] = false;
19             position[index] = 0;
20         }
21         
22         for(index = 0; index < s.size(); ++ index)
23         {
24             if(exist[s[index]])
25             {
26                 for(rangeIndex = start; rangeIndex <= position[s[index]]; ++ rangeIndex)
27                 {
28                     exist[s[rangeIndex]] = false;
29                 }
30                 start = position[s[index]] + 1;
31                 exist[s[index]] = true;
32             }else
33             {
34                 exist[s[index]] = true;
35                 maxLen = (maxLen < index - start + 1) ? index - start + 1:maxLen;
36             }
37             
38             position[s[index]] = index;
39         }
40         
41         return maxLen;
42     }
43 };
View Code

 

转载于:https://www.cnblogs.com/Shirlies/p/5736696.html

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值