# 1. 求字符串的最长不重复子串的长度

• abcabcbb，返回abc
• bbbbb，返回b
• pwwkew，返回wke。注意pwke是子序列，不是子串

• 当字符串为abcdace，而i=5时，left应该为3。此时i-left+1=3,而之前求得的最长不重复子串的长度是4>3，所以i=5时的结果是4。

public class Solution {
public int lengthOfLongestSubstring(String str) {
if(str==null||str.length()==0)
return 0;
char[] cs = str.toCharArray();
int[] charMap = new int[256];
Arrays.fill(charMap , -1);
int max = 0;
int left = 0;
for(int i=0;i<cs.length;i++){
if(charMap[cs[i]]>=left)
left = charMap[cs[i]]+1;
int tmp = i-left+1;
if(tmp>max)
max = tmp;
charMap[cs[i]]=i;
}
return max;
}
}

# 2. 两个字符串的最长公共子串

public String getLongestCommonSubstring(String str1, String str2){
//check input parameters
if(str1==null||str2==null)
return null;
//find out the bigger string and the smaller one
String big = str1.length()>=str2.length()?str1:str2;
String small = str1.length()<str2.length()?str1:str2;
//get the end of the longest common substring in small
int[] help = new int[small.length()];
int end = 0;
int length = 0;
for(int i=0;i<big.length();i++){
for(int j=small.length()-1;j>=0;j--){
if(big.charAt(i)==small.charAt(j)){
if(j==0)
help[j]=1;
else{
help[j]=help[j-1]+1;
if(help[j]>length){
length = help[j];
end = j;
}
}
}else
help[j]=0;
}
}
//get the longest common substring and return it
if(length==0)
return null;
else
return small.substring(end-length+1,end+1);
}