您的位置:首页 > 编程语言 > C语言/C++

leetcode 3. Longest Substring Without Repeating Characters的c语言解决

2018-03-09 14:03 441 查看
问题描述:

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.
解决思路:算出每个字符开始不重复最长字符串数,例如'pwwkew', 从'p'开始最长不重复字符串数为2,从第一个'w'开始的为1,从第二个'w'开始的为3,这样比较下去,代码如下int lengthOfLongestSubstring(char* s) {
if(!strlen(s)) return 0;
int ans = 1, tmp = 1;
int k;
for(int i = 0; i<strlen(s); i++){
for(int j = i+1; j<strlen(s); j++){
for(k=i; k<j; k++){
//看j对应的字符在i到j之间是否重复,如有跳出第三层循环
if(s[k] == s[j])
break;
}
//不重复的情况
if(k == j)
tmp++;
//当有重复的时候,直接结束第二层循环,回到第一个循环检查下一字符
else
break;
}
ans = (ans>tmp)?ans:tmp;
tmp = 1;
}
return ans;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: