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
Given
Given
解决思路:算出每个字符开始不重复最长字符串数,例如'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;
}
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;
}
相关文章推荐
- LeetCode 3. Longest Substring Without Repeating Characters (C语言)
- LeetCode-3-Longest Substring Without Repeating Characters(C语言实现)
- 【C语言】LeetCode 3. Longest Substring Without Repeating Characters
- LeetCode:Longest Substring Without Repeating Characters(最长不重复子串)
- leetcode 3 Longest Substring Without Repeating Characters
- leetcode_3Longest Substring Without Repeating Characters
- leetcode 第三题Longest Substring Without Repeating Characters
- Leetcode解题笔记 3.Longest Substring Without Repeating Characters [Medium]
- [LeetCode] Longest Substring Without Repeating Characters
- LeetCode 3. Longest Substring Without Repeating Characters(java)
- [leetcode3] Longest Substring Without Repeating Characters
- LeetCode_Longest Substring Without Repeating Characters
- [leetcode] Longest Substring Without Repeating Characters
- [Leetcode]Longest Substring Without Repeating Characters
- Leetcode: longest-substring-without-repeating-characters
- Leetcode—3.Longest Substring Without Repeating Characters
- [LeetCode]Longest Substring Without Repeating Characters
- LeetCode之Longest Substring Without Repeating Characters
- LeetCode 3. Longest Substring Without Repeating Characters [Medium]
- Leetcode 3. Longest Substring Without Repeating Characters(java版)