描述:
给定一个字符串,请找出其中无重复字符的最长子字符串。
样例:
例如,在"abcabcbb"
中,其无重复字符的最长子字符串是"abc"
,其长度为 3
。
对于,"bbbbb"
,其无重复字符的最长子字符串为"b"
,长度为1
。
思路:
逐个字符起开始遍历,创建哈希表来存储元素
public class Solution {
/**
* @param s: a string
* @return: an integer
*/
public int lengthOfLongestSubstring(String s) {
// write your code here
if(s == null || s.length() == 0){
return 0;
}
int result = 0;
for(int i = 0;i<s.length();i++){
int count = 0;
HashSet<Character> temp = new HashSet<Character>();
temp.add(s.charAt(i));
count++;
for(int j = i+1;j<s.length();j++){
if(temp.contains(s.charAt(j))){
break;
}else{
temp.add(s.charAt(j));
count++;
}
}
result = Math.max(result,count);
}
return result;
}
}