字符串最长不重复字符序列
转载请注明作者与出处:franciscolv http://www.cnblogs.com/franciscolv/archive/2011/11/20/2255852.html
package SortSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 最长不重复子串 注意最后的时候比较i-start和最长子串的情况 以防止丢失值
*
* @author franciscolv
*
*/
public class MaxLenSubString {
public static void main(String[] args) {
List<String> result = maxLenSubString("absccdfkmnok");
for (String s : result)
System.out.println(s);
}
/**
* o(n)获取最大长度 o(n*n)构造全部结果
*
* @param s
* @return
*/
public static List<String> maxLenSubString(String s) {
char[] c = s.toCharArray();
Map<Character, Integer> charMap = new HashMap<Character, Integer>();
List<String> maxSubList = new ArrayList<String>();
int start = 0, max = 0;
int i = 0;
for (; i < c.length; i++) {
if (charMap.containsKey(c[i])) {
int tmp = i - start;
int pos = charMap.get(c[i]);
if (tmp >= max) {
if (tmp > max)
maxSubList.clear();
/**
* 这里需要o(n)才能构建出子串
*/
maxSubList.add(s.substring(start, i));
charMap.put(c[i], i);
max = tmp;
} else
charMap.put(c[i], i);
start = pos + 1;
} else
charMap.put(c[i], i);
}
if (i - start >= max) {
if (i - start > max) {
maxSubList.clear();
max = i - start;
}
maxSubList.add(s.substring(start, i));
}
System.out.println(max);
return maxSubList;
}
}