您的位置:首页 > 编程语言 > Go语言

[LeetCode-Algorithms-3] "Longest Substring Without Repeating Characters" (2017.9.8)

2017-09-08 21:47 375 查看

题目链接: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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: