[LeetCode-Algorithms-3] "Longest Substring Without Repeating Characters" (2017.9.8)
来源:互联网 发布:ipad不良信息过滤软件 编辑:程序博客网 时间:2024/06/05 18:51
题目链接:Longest Substring Without Repeating Characters
- 题目描述:
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.
<1>题目思路:贪心,用两变量标记头尾,lon为所求的不重复字符串长度,从字符串头部开始,字符不重复时尾部变量往后增加,有字符和之前的字符串中某字母重复时,头部变量相应后推,由于使用内外双层循环,时间复杂度为O(n2) 。
<2>代码:
int lengthOfLongestSubstring(char* s) { int len = strlen(s); int lon = 0, i; int bgt = 0, end; for(end = 0; end < len; end++){ for(i = bgt; i < end; i++) { if(s[end] == s[i]) bgt = i + 1; } if(lon <= end - bgt) lon = end - bgt + 1; } return lon;}
<3>提交结果:
<4>向他人学习:我在讨论中看到了C++的一种解法,52.2%的defeat率,觉得想法也是比较好,留在这里作为学习。
class Solution {public: int lengthOfLongestSubstring(string s) { int last[128]; int start = -1, ans = 0; for(int i = 0; i < 128; i++) last[i] = -1; for(int i = 0; i < s.length(); i++) { if (last[s[i]] > start) start = last[s[i]]; last[s[i]] = i; ans = ans > i-start ? ans : i-start; } return ans; }};
阅读全文
0 0
- [LeetCode-Algorithms-3] "Longest Substring Without Repeating Characters" (2017.9.8)
- LeetCode Algorithms 3. Longest Substring Without Repeating Characters 题解
- LeetCode Algorithms 3. Longest Substring Without Repeating Characters
- leetcode Algorithms 3. Longest Substring Without Repeating Characters
- [LeetCode] Algorithms-3.Longest Substring Without Repeating Characters
- LeetCode 3 - Longest Substring Without Repeating Characters
- LeetCode 3: Longest Substring Without Repeating Characters
- leetcode-3:Longest Substring Without Repeating Characters
- LeetCode(3) Longest Substring Without Repeating Characters
- leetcode 3LONGEST SUBSTRING WITHOUT REPEATING CHARACTERS
- Leetcode【3】:Longest Substring Without Repeating Characters
- [leetcode 3] Longest Substring Without Repeating Characters
- [Leetcode] 3 - Longest Substring Without Repeating Characters
- LeetCode 3:《Longest Substring Without Repeating Characters》
- [leetcode 3] Longest Substring Without Repeating Characters
- [leetcode] 3 Longest Substring Without Repeating Characters
- [Leetcode]3Longest Substring Without Repeating Characters
- leetcode 3 Longest Substring Without Repeating Characters
- android 沉浸式2种
- Java基础之集合框架--Collection根接口(集合框架的共性功能)
- Ubuntu常用命令大全
- Unity3D-Transform
- JQuery给动态添加的元素绑定事件
- [LeetCode-Algorithms-3] "Longest Substring Without Repeating Characters" (2017.9.8)
- myeclipse所有快捷键
- 多个项目配置在同一个tomcat下的问题
- C/C++ 调用 Lua 函数(非全局函数)
- ubuntu 14.04 截屏快捷键
- 【数据结构----笔记3】插入排序算法之【直接插入排序】
- Java集合框架(1)
- Java语言基础小结2
- bzoj1113[Poi2008]海报PLA 单调栈