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
原创粉丝点击