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.
#include<iostream>
#include <string>
using namespace std;
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int i = 0, j = 0;
int str_len = s.length();
int substr_len = 0;
int substr_index = 0;
int pos_index = 0;
int sub_pos_index = 0;
while(i < str_len){
j = 0;
string substr = s.substr(i, str_len);
substr_index = substr.length();
while(j < substr_index){
sub_pos_index = substr.find(substr[j], j + 1);
if(sub_pos_index != string::npos){
substr_index = sub_pos_index;
substr = substr.substr(0, substr_index);
}
j++;
}
if(substr_len < j){
pos_index = i;
substr_len = j;
}
i++;
}
return substr_len;
}
};
int main()
{
Solution a;
int value = 0;
string s("abcabcbb");
value = a.lengthOfLongestSubstring(s);
cout << "length = " << value << endl;
system("pause");
return 0;
}
本文介绍了一种解决最长无重复字符子串问题的方法。通过使用C++编程语言实现了一个算法,该算法能够找到给定字符串中最长的不包含重复字符的子串,并返回其长度。示例中给出了具体的实现过程及测试案例。
462

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



