寻找最长没有重复字母的substring
Note that BF will take too much time!
这题的特点在于如果出现一次重复就可以直接从重复的那个字符开始继续往后面搜,那么就可以用一个HashMap来存每个字母的last occurence。
记录下前面的non-repeated substring的长度,update the result number iff another max length exists。
class Solution {
public int lengthOfLongestSubstring(String s) {
//Use a hashmap to record the latest occurence of a character (indices)
HashMap <Character, Integer> hm = new HashMap <>();
int res = 0;
//i is the fast pointer and j is the one at the beginning of a non-repeated
//substring
for (int i = 0, j = 0; i < s.length(); i++){
if(hm.containsKey(s.charAt(i))){
//j could not go backwards, so its value can only increase
j = Math.max(j, hm.get(s.charAt(i)) + 1);
}
hm.put(s.charAt(i), i);
res = Math.max(res, i-j+1);
}
return res;
}
}
Longest Palindromic Susbtring - DP solution
因为palindrome string从两端往中间挤的情况下,inside string依然是个palindrom,所以是可以用dp的。
i是substring的起始index,j是结束index,如果创建一个2d boolean数组的话,长和宽应该是题目给的string的长度。但是i<j的情况下的那些element是不会被遍历的(常理)。
什么时候应该set the location to be true?
首先palindrome的首末两个字母肯定是要相等的,如果不相等可以直接为false。
如果bb这种情况,属于b==b以及字符长度为2。
如果是b这种情况(就一个字母),肯定也是palindrome的,此时长度为1。
辣么bab这种情况呢,就是当首位字母都相等的时候检查inside的substring是不是个palindrome:dp[i+1][j-1]的值。(因为i是我们正在探索的substring的头,j是substring的尾,所以头+1和尾-1构成的substring除首尾之外的substring。)如果碰巧这个inside substring也是palindrome,那么dp[i][j]=true没得跑了。
class Solution {
public String longestPalindrome(String s) {
int len = s.length();
String res = "";
if(s.length() == 0 || s == null){
return res;
}
boolean dp [][] = new boolean [len][len];
for(int i = len - 1; i >=0; i--){
for (int j = i; j < len; j++){
if(s.charAt(i) == s.charAt(j) && (j-i < 3 || dp[i+1][j-1])){
dp[i][j] = true;
}else{
dp[i][j] = false;
}
//updating the res
if(dp[i][j] && (j-i+1 > res.length() || res == null)){
res = s.substring(i, j+1);
}
}
}
return res;
}
}