简介
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: “abcabcbb”
Output: 3
Explanation: The answer is “abc”, with the length of 3.
Example 2:
Input: “bbbbb”
Output: 1
Explanation: The answer is “b”, with the length of 1.
Example 3:
Input: “pwwkew”
Output: 3
Explanation: 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.
解题思路
类似于桶排序,将每一个字符对应的ASII码依依进行匹配。
初始化数组为0,从第一个字符开始匹配,若数组为0,说明没有匹配到,将其置为1;
若为1,即匹配的已存在,则说明出现重复;
记录当前子串数,从第二个字符开始重新匹配,直到把整个字符串匹配完
代码
#include <iostream>
#include <string>
#include <memory.h>
using namespace std;
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int num[127] = {0}; //对应ASII码
// printArray(num);
// cout << endl;
int n = 0; //记录每次最大的子串数
int strlen = s.length(); //字符串长度
cout << "strlen:" << strlen << endl;
for(int i = 0; i < strlen; i++)
{
for(int j = i; j < strlen; j++)
{
// if(num[(int)s[j]-97] == 0)
if(num[(int)s[j]] == 0) //未出现重复
{
// num[(int)s[j]-97] = 1;
num[(int)s[j]] = 1;
//printArray(num);
// cout << "frist: " << endl;
n++;
if(length < n)
{
length = n;
}
// cout << "length:" << length << " " << "n:" << n << endl;
}
else //出现重复
{
memset(num, 0, sizeof(num)); //将数组num全置为0
// printArray(num);
// cout << "sencond: " << endl;
n = 0;
break;
}
}
}
return length;
}
void printArray(int num[]) //遍历数组
{
for(int i = 0; i < 127; i++)
{
cout << num[i] << " ";
}
}
private:
int length = 0;
};
int main()
{
string str;
cin >> str;
Solution su;
// cout << endl;
cout << su.lengthOfLongestSubstring(str);
return 0;
}