Leetcode Problem Set
Algorithm Question 3
Problem description:
Given a string, find the length of the longest substring without repeating characters.
Example:
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.
Thinking
To calculate length of the longest substring, firstly we need to obtain the longest one. Here I have used a stupid way: detect substring by different beginning character, thus I can use loop to start detection. We assume the first loop is indexed by ‘i’, inside the loop, I have made an inner loop, indexed by ‘j’, in this loop, each element is regarded as candidate element for our longest substring, we add it up to our substring first, to check whether it is legal, we need another inner loop, to find the character is not similiar with former characters. Finally we get the longest substrings in different ‘i’ iterations, the very last step is compare them to pick up a longest one overall.
Code:
// written in C++
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int i ,j;
string sub1, sub2;
for (i = 0; i < s.length(); i++) {
sub2.clear();
sub2 += sub1;
sub1.clear();
sub1.push_back(s[i]);
// sub2 store sub1 value temporarily
// iterate substrings begin with each character
for (j = i+1; j < s.length(); j++) {
sub1.push_back(s[j]);
bool stop = false;
for (int k = i; k < j; k++) {
if (s[j] == s[k]) {
sub1.pop_back();
stop = true;
break;
} // if reapated, delete that c
}
if (stop) break;
}
if(sub1.length() < sub2.length()) {
sub1.clear();
sub1 += sub2;
}
}
return sub1.length();
}
}
edited by Maoyuan, SYSU