Longest Substring Without Repeating Characters 最长不重复子串【中】
来源:互联网 发布:星型网络 编辑:程序博客网 时间:2024/06/06 00:56
Longest Substring Without Repeating Characters
给定一个字符串,寻找最长不重复子串长度。
难度:中等
比如:
"abcabcbb",结果是"abc" 长度为3
“bbbbb” 结果为b,长度为1
"pwwkew" 结果为wke,长度为3
此题很容易想到O(n^3)的解法即枚举所有子串O(n^2),然后判断每个子串是否有重复的字符O(n),所以总的时间复杂度为O(n^3)。当然如果这样解的话就丧失了这道题的意义了(不知道这种解法会不会超时)。下面介绍一个O(n^2)的解法。
对于任意一个子串ai,ai+1,ai+2,ai+3......aj 假设这个子串内部没有重复的字符,那麼当aj+1加入的时候只需要判断aj+1在之前找到的子串内部有没有相同的字符O(n),假设存在一个字符ak满足ak==aj+1,那麼刚刚找到的[ai,aj]子串就需要从位置k处断开来接受aj+1即变成[ai,ak],[ak+1,aj+1]此时计算子串长度合法的子串集合有[ai,ak],[ak+1,aj+1],[ai,aj],比较三种子串那个比较长即可结果保存在iResult里面,然后j往后继续组子串每次碰到有相同的字符的时候就根据上述的三个子串那个较长即可O(n),所以总复杂度为O(n^2)。代码如下:
class Solution {public: int lengthOfLongestSubstring(string s) { int i, j, k = -1;//程序开始时,k位置不存在所以初始值为-1 int iLen = s.length(); int iResult = 1; for(j = 1; j < iLen; j ++)//扫描ai,ai+1,ai+2....aj,寻找位置k { for(i = j - 1; i > k; i --) { if(s[i] == s[j]) { k = i; break; } } iResult = iResult > (j - i) ? iResult : (j - i);//取值 } if(iLen == 0) iResult = 0; return iResult; }};
0 0
- Longest Substring Without Repeating Characters 最长不重复子串【中】
- leetcode 3. Longest Substring Without Repeating Characters 最长不重复子串和重复子串
- LeetCode Longest Substring Without Repeating Characters 最长不重复子串查找
- 【LeetCode】Longest Substring Without Repeating Characters && 【九度】题目1530:最长不重复子串
- Longest Substring Without Repeating Characters 不含重复字符的最长子串
- leetcode-Longest Substring Without Repeating Characters 最长不重复子串
- LeetCode | Longest Substring Without Repeating Characters(最长连续不重复子串)
- Longest Substring Without Repeating Characters 最长不重复子串 @LeetCode
- Longest Substring Without Repeating Characters (最长不重复子串)
- [C++]LeetCode 3: Longest Substring Without Repeating Characters(最长不重复子串)
- Leetcode Longest Substring Without Repeating Characters(最长不重复子串)
- [leetcode]Longest Substring Without Repeating Characters【最长不重复字符子串】
- leetcode系列(31)Longest Substring Without Repeating Characters 最长不重复子串
- LeetCode 3. Longest Substring Without Repeating Characters(最长不重复子串)
- Longest Substring Without Repeating Characters 最长不重复的子串
- LeetCode3. Longest Substring Without Repeating Characters(最长不重复子串)
- LeetCode OJ:Longest Substring Without Repeating Characters(最长不重复子串)
- 03 最长不重复子串Longest Substring Without Repeating Characters
- 142. Linked List Cycle II
- 黑马4到9天
- POJ 1595 Prime Cuts 未完成
- 玲珑学院ACM比赛 Round #5 Aplus B
- Java Web J2EE下的两大框架SSH和SSM对比
- Longest Substring Without Repeating Characters 最长不重复子串【中】
- bellman ford 算法 判断是否存在负环
- Linux编程:进程间通信--消息队列
- FreeBSD下配置vim和ctags
- Tensorflow系列——基本用法
- 火狐粉丝见面会总结
- org.hibernate.PropertyValueException: not-null property references a null or transient value : xxx
- Android自动化压力测试图解教程——Monkey工具
- qwdqwdqw