题目地址:Longest Substring Without Repeating Characters
题目简介:给定一个字符串,找到最长的无重复字符串
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.
题目思路:
根据人为的寻找习惯,应该从左到右以此遍历字符串,在出现重复字符串时重新寻找子字符串。字符串中对应的ASCII码中的256个字符,为了方便记下这256个字符可能出现的位置,所以可以用一个数据结构存储他们的位置。
C++版:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int v[256]; //用来存储256个字符的位置
memset(v,-1,sizeof(v)); //刚开始所有的位置均未初始化
int len = s.length(), ans = 0,start = -1;//获得字符串的长度,ans代表最终的结果,start代表
//子字符串的其实位置
if (len <= 1) //如果输入的字符串为空或只有一个字符
return len;
for(int i = 0;i < len;i++)
{
if(v[s[i] - ' '] > start) //若下一个可以加入的字符在之前出现过,则更新子字符串的起始位置
start = v[s[i] - ' '];
v[s[i] - ' '] = i; //当前子字符串能到达的位置
ans = max(ans,i - start);//更新最终的结果
}
return ans;
}
};
Python版:
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
length = len(s) #获得字符串长度
if length <= 1:
return length
start = -1
ans = 0
list1 = [-1] * 256 #列表初始化为256个-1
for i in range(0,length):
if list1[ord(s[i]) - ord(' ')] > start:
start = list1[ord(s[i]) - ord(' ')];
list1[ord(s[i]) - ord(' ')] = i
ans = max(ans, i - start)
return ans