leetcode 3:无重复字符的最长子串
2018-09-14 15:22
393 查看
给定一个字符串,找出不含有重复字符的最长子串的长度。
示例 1:
输入: "abcabcbb" 输出: 3 解释: 无重复字符的最长子串是 "abc",其长度为 3。
示例 2:
输入: "bbbbb" 输出: 1 解释: 无重复字符的最长子串是 "b",其长度为 1。
示例 3:
输入: "pwwkew" 输出: 3 解释: 无重复字符的最长子串是 "wke",其长度为 3。 请注意,答案必须是一个子串,"pwke"是一个子序列 而不是子串。j
解法一:
[code]int lengthOfLongestSubstring(char *s) { int length = strlen(s); char *temps = (char *)malloc(length*sizeof(char));//辅助数组 int count = 0;//辅助数组index int start = 0;//最长字符串起始index int len = 0;//最长字符串长度 bool isok = true; for (int i = 0; i < length;) { if (isok) temps[count++] = s[i++];//加入新元素 isok = true;//标志位置位 for (int j = start; j < count-1; j++)//检测新加入的元素是否已经存在 { if (temps[j] == s[i-1])//如果已经存在,break,起始字符后移 { isok = false;//标志位置位 start++;//起始字符后移 break; } } len = len>(i - start) ? len : (i - start);//计算长度 } return len; }
解法二:发现自己蠢了,不用建立什么辅助数组,建立个头尾用滑窗就好啦
[code]int lengthOfLongestSubstring(char* s) { int start = 0, end = 1;//设置滑窗头尾 int maxlen = 1;//最大长度 if (!strlen(s)) { return 0; } else if(strlen(s) == 1) { return 1; } int len = strlen(s); for(;end<len;end++) { for(int i = start;i<end;i++) { if(*(s+i) == *(s+end))//比较下一个元素和滑窗已有元素 { start = i + 1; break; } } if ((end - start)+1 > maxlen)//比较大小 maxlen = (end - start) + 1; } return maxlen; }
解法三:利用map容器
[code]class Solution { public: /** * @param s * @return */ int lengthOfLongestSubstring(string s) { // write your code here int ret = 0; map<char, int> m; int start = 1; for (int i = 1; i <= s.length(); i++) { char c = s[i - 1]; if (m[c] >= start) { start = m[c] + 1; m[c] = i; } else { m[c] = i; ret = max(ret, i - start + 1); } } return ret; } };
阅读更多
相关文章推荐
- LeetCode题库解答与分析——#3.无重复字符的最长子串LongestSubstringWithoutRepeatingCharacters
- LeetCode 无重复字符的最长子串
- LeetCode - 无重复字符的最长子串
- 【LeetCode】3. 无重复字符的最长子串(Longest Substring Without Repeating Characters,24.2%,中等)
- LeetCode 3. 无重复字符的最长子串
- Leetcode:395至少有K个重复字符的最长子串(C++)
- LeetCode-3:Longest Substring Without Repeating Characters (最长无重复字符的子串) --medium
- 【LeetCode】3.无重复字符的最长子串 结题报告 (C++)
- LeetCode 3. 无重复字符的最长子串 Python
- [LeetCode]3. Longest Substring Without Repeating Characters寻找最长无重复字符的子串
- 【leetcode】第3题:求最长不重复(字符不重复)的子串的长度
- leetcode(3)无重复字符的最长子串
- LeetCode 3. Longest Substring Without Repeating Characters--不包含重复字符的最长子串长度
- LeetCode 3 无重复字符的最长子串(哈希表或数组)
- 【LeetCode题目记录-3】字符串中最长的没有重复字符的子串
- leetcode:Longest Substring Without Repeating Characters (寻找最长无重复字符的子串)
- leetcode-最长无重复字符的子串
- [leetcode]无重复字符的最长子串
- 【LeetCode】无重复字符的最长子串
- Leetcode 3. 无重复字符的最长子串