LeetCode3. Longest Substring Without Repeating Characters
来源:互联网 发布:知天命什么意思 编辑:程序博客网 时间:2024/06/03 14:09
LeetCode3. 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.
题目分析 :一看到题目,第一时间想到的就是用set,但是觉得用set还不如直接用一个a[256]的数组。然后用一个max来记录最大长度,然后用了O(n^2)的时间复杂度来实现。
自己的代码:
class Solution {public:int lengthOfLongestSubstring(string s) {//set<char> tset;if (s.empty()) return 0;int tmax = 1;int i, j;for (i = 0; i < s.size() - 1 - tmax + 1; i++) {char a[257] = { 0 };a[s[i]] = 1;for (j = i + 1; j < s.size(); j++) {if (a[s[j]] == 0) {a[s[j]]++;}else {tmax = tmax > j - i ? tmax : j - i;break;}}int size = 0;for (int k = 0; k < 256; k++) {if (a[k]) size++;}tmax = tmax > size ? tmax : size;}//tmax = tmax > tset.size() ? tmax : tset.size();return tmax;}};
但是觉得自己的复杂度有点高,看了一下别人的算法,只用了O(n)的时间复杂度。
代码如下:
int lengthOfLongestSubstring(string s) { vector<int> dict(256, -1); int maxLen = 0, start = -1; for (int i = 0; i != s.length(); i++) { if (dict[s[i]] > start) start = dict[s[i]]; dict[s[i]] = i; maxLen = max(maxLen, i - start); } return maxLen;}
阅读全文
0 0
- LeetCode3:Longest Substring Without Repeating Characters
- [LeetCode3] Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters leetcode3
- LeetCode3 Longest Substring Without Repeating Characters
- LeetCode3:Longest Substring Without Repeating Characters
- leetcode3 longest Substring Without Repeating Characters
- LeetCode3:Longest Substring Without Repeating Characters
- Leetcode3 Longest Substring Without Repeating Characters
- leetcode3--Longest Substring Without Repeating Characters
- leetcode3. Longest Substring Without Repeating Characters
- LeetCode3:Longest Substring Without Repeating Characters
- Leetcode3:Longest Substring Without Repeating Characters
- [leetcode3] Longest Substring Without Repeating Characters
- Leetcode3 : Longest Substring Without Repeating Characters
- LeetCode3. Longest Substring Without Repeating Characters
- LeetCode3. Longest Substring Without Repeating Characters
- leetcode3. Longest Substring Without Repeating Characters
- LeetCode3. Longest Substring Without Repeating Characters
- ActiveMQ系列—ActiveMQ集群方案(上)(高性能方案)
- udp客户端与服务端相连时,握手情况的处理
- JVM菜鸟进阶高手之路十二(jdk9、JVM方面变化, 蹭热度)
- 什么?!不用敲键盘也能get到excel代码啦?
- 剑指offer-链表中倒数第K个结点
- LeetCode3. Longest Substring Without Repeating Characters
- Hadoop 解除 "Name node is in safe mode"
- java中的IO
- 关于JEESJS的内容支持
- 基于图像形状的一种比较漂亮的分类算法
- fedora安装Telnet
- 装饰模式
- [LeetCode-Algorithms-23] "Merge k Sorted Lists" (2017.9.22-WEEK3)
- 一道好玩的逻辑题之蓝眼睛红眼睛