题目:
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.
链接:https://leetcode.com/problems/longest-substring-without-repeating-characters/
答案:
参考了这个链接后才明白解题思路,然后依据自己的理解写了代码。
大致思路是:从当前字符开始,往前看,没有出现过重复字符的字符串
代码:
1 #define MAX_LETTER_NUM 255 2 class Solution { 3 public: 4 int lengthOfLongestSubstring(string s) { 5 if(s.empty()) 6 { 7 return 0; 8 } 9 10 bool exist[MAX_LETTER_NUM]; 11 int position[MAX_LETTER_NUM]; 12 int index,rangeIndex; 13 int maxLen = 0; 14 int start = 0; 15 16 for(index = 0; index < MAX_LETTER_NUM; ++ index) 17 { 18 exist[index] = false; 19 position[index] = 0; 20 } 21 22 for(index = 0; index < s.size(); ++ index) 23 { 24 if(exist[s[index]]) 25 { 26 for(rangeIndex = start; rangeIndex <= position[s[index]]; ++ rangeIndex) 27 { 28 exist[s[rangeIndex]] = false; 29 } 30 start = position[s[index]] + 1; 31 exist[s[index]] = true; 32 }else 33 { 34 exist[s[index]] = true; 35 maxLen = (maxLen < index - start + 1) ? index - start + 1:maxLen; 36 } 37 38 position[s[index]] = index; 39 } 40 41 return maxLen; 42 } 43 };
本文探讨LeetCode上一道经典题目:寻找给定字符串中最长的无重复字符子串。通过详细解析算法思路,分享了一种高效求解方法,并附上了C++实现代码。
573

被折叠的 条评论
为什么被折叠?



