题目要求:
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 String lengthOfLongestSubstring(String s) ;
思想很简单,我们假设String s长度为n。 那么s是由前n-1个字母和最后一个字母组成,这个函数返回当前string从结尾开始的最长不重复子串。
算法的流程:
1. 如果s的长度为1,直接返回s。
2. 如果s的长度大于1,那么假设前n-1个字母组成的字符串尾部的最长不重复子串为prefix。 查找最后一个字母是否在prefix中出现:
2.2 如果否,那么把这个字符append到prefix上返回。
2.3 如果是,那么用这个字符来split这个prefix,然后把这个字符append到得到的String数组的最后一个元素上返回。
注意一点,这个算法并不直接返回最大子串的长度,而是将最大长度,或者也可以有最大子串作为一个全局变量,在每次函数返回的时候比较是否当前长度大于最大长度,如果是则重置最大长度和最大子串。
public String _lengthOfLongestSubstring(String s) {
if (s == null || s.length() == 0) {
return "";
}
if (s.length() == 1) {
max = 1;
maxString = s;
return s;
}
String prefix = _lengthOfLongestSubstring(s
.substring(0, s.length() - 1));
String c = s.substring(s.length() - 1);
if (prefix.contains(c)) {
if (prefix.length() > max) {
max = prefix.length();
maxString = prefix;
}
String[] seq = prefix.split(c);
String result = seq.length >= 1 ? seq[seq.length - 1].concat(c) : c;
return result;
} else {
String result = prefix.concat(c);
if (result.length() > max) {
max = result.length();
maxString = result;
}
return result;
}
}
第二种解法,就是第一种解法的循环版本。
public int lengthOfLongestSubstring(String s) {
int max = 0;
StringBuffer temp = new StringBuffer();
for (int i = 0; i < s.length(); i++) {
Character c = s.charAt(i);
if (temp.toString().contains(c.toString())) {
temp = new StringBuffer(temp.substring(
temp.lastIndexOf(c.toString()) + 1, temp.length()));
temp.append(c);
} else {
temp.append(c);
if (temp.length() > max) {
max = temp.length();
}
}
}
return max;
}
第三种解法,也是循环。
这种解法记录当前扫描到的串的起始和结束位置,并用一个hashmap来保存当前串中字符的位置(也可以用一个int数组: int[] map = new int[256])。
1. 初始化max=0, 起始的start和end都在0的位置,用一个循环不断向后挪动end。
2. 如果当前的end指向的字符在hashmap中存在,那么扫描当前start到当前end中所有的字符,并从hashmap中清空。 然后将start挪动到hashmap中保存的end对应的位置的后一位。
3. 将当前的end位置存入hashmap。
4. 查看当前的 end - start + 1是否大于max, 如果是则更新max的值。
public int lengthOfLongestSubstring(String s) {
int max = 0;
Map<Character, Integer> map = new HashMap<Character, Integer>();
// inclusive
int start = 0;
int end = 0;
while (end < s.length()) {
Integer index = map.get(s.charAt(end));
if (index != null) {
for (int i = start; i <= index; i++) {
map.remove(s.charAt(i));
}
start = index + 1;
}
map.put(s.charAt(end), end);
if (end - start + 1 > max) {
max = end - start + 1;
}
end++;
}
return max;
}
转载于:https://blog.51cto.com/kcy1860/1263882