算法分析与设计——LeetCode:3. Longest Substring Without Repeating Characters
2017-09-24 16:23
621 查看
题目
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.class Solution {
public:
int lengthOfLongestSubstring(string s) {
};
思路
从左到右遍历,每个字母都与从head到它本身的所有字母比较是否相同,如果相同,则说明当前的substring已经不能再扩大了,将其长度与当前最大值取最大,并且将head直接移动到与当前字母(i)相同的字母(j)处的下一个,这样可以尽可能的减少重复的比较,因为上一个head第j个字母之间的每个字母作为head,到第i个字母时都会因为第j个字母的相同而使substring无法扩大,substring都小于上一个head到第i个字母。假设string长度为n,第一个循环将进行n次,第二个循环次数不会超过26(若全为小写)。代码
class Solution { public: int lengthOfLongestSubstring(string s) { int head = 0, max = 0, current = 0; int size = s.size(); int i, j; for (i = 0; i < size; i++) { for (j = head; j < i; j++) { if (s[j] == s[i]) { break; } } if (j == i) { current++; } else { if (current > max) { max = current; } current = current-(j-head);//从新的head到当前字母位置的substring的长度 head = j+1;//移动head } } if (current > max) { max = current; } return max; } };
相关文章推荐
- 算法分析与设计——LeetCode Problem.3 Longest Substring Without Repeating Characters
- [算法分析与设计] leetcode 每周一题:Longest Substring Without Repeating Characters
- 算法分析与设计——LeetCode Problem.3 Longest Substring Without Repeating Characters
- 数据结构与算法[LeetCode]—Longest Substring Without Repeating Characters
- 每周LeetCode算法题(一):Longest Substring Without Repeating Characters
- (算法分析Week19)Longest Substring Without Repeating Characters 最长无重复子串 [Medium]
- LeetCode题解 || Longest Substring Without Repeating Characters (O(n)算法)问题
- LeetCode题库解答与分析——#3.无重复字符的最长子串LongestSubstringWithoutRepeatingCharacters
- LeetCode题解 || Longest Substring Without Repeating Characters (O(n)算法)问题
- 【LeetCode-面试算法经典-Java实现】【003-Longest Substring Without Repeating Characters(最长非重复子字符串)】
- LeetCode算法题目:Longest Substring Without Repeating Characters
- leetcode:Longest Substring Without Repeating Characters (双指针扫描) 【面试算法题】
- LeetCode算法问题7 —— Longest Substring Without Repeating Characters
- leetcode 3 Longest Substring Without Repeating Characters最长无重复子串
- LeetCode 003 Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters (LeetCode)
- LeetCode - Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters(LeetCode)
- leetcode-Longest Substring Without Repeating Characters
- LeetCode 第三题,Longest Substring Without Repeating Characters