您的位置:首页 > 编程语言 > Java开发

[Leetcode] Longest Substring Without Repeating Characters (Java)

2013-12-26 17:27 567 查看
Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without
repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

找最长不重复子串,即找字符串,不存在相同字符,找到最长的一个

public class LongestSubstringWithoutRepeatingCharacters {
public int lengthOfLongestSubstring(String s) {
int max = 0;
boolean[] bit = new boolean[26];
int start = 0;
int tempMax = 0;
for(int i=0;i<s.length();i++) {
if(bit[s.charAt(i)-'a']){
if(max < tempMax)
max = tempMax;
for(int j = start;j<i;j++) {
if(s.charAt(j)!=s.charAt(i)) {
bit[s.charAt(j)-'a'] = false;
tempMax--;
}
else {
start = j+1;
break;
}
}
}else {
bit[s.charAt(i)-'a'] = true;
tempMax++;
}
}
return max>tempMax?max:tempMax;
}
public static void main(String[] args) {
String string = new String("qopubjguxhxdipfzwswybgfylqvjzhar");
int result = new LongestSubstringWithoutRepeatingCharacters().lengthOfLongestSubstring(string);
System.out.println(result);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: