您的位置:首页 > 其它

3. Longest Substring Without Repeating Characters

2016-05-14 14:52 453 查看
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.

public class Solution {
public int lengthOfLongestSubstring(String s) {
int[] last = new int[128];
int start = 0;
int len = 0;
char[] w = new char[s.length()];
w = s.toCharArray();
for(int i = 0; i < 128; i++)
last[i] = -1;//last数组用于保存新出现的字符的下标,一开始全部初始化为-1
for(int i = 0; i < s.length(); ++i){
if(last[w[i]-' '] >= start){ //当前这个字符出现过
if(i-start > len)
len = i-start;
start = last[w[i]-' '] + 1; //从这个字符首次出现的位置+1,重新扫描,相当于把前面抛开前面的字符串不谈
}
last[w[i]-' '] = i;//更新当前字符的下标
}
if(len > s.length() - start)//针对没有重复字符的字符串
return len;
else
return s.length() - start;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: