字符串最后一天,明天开哈希表,人已在图书馆发疯:)
5 Longest Palindromic Substring
class Solution {
public:
string longestPalindrome(string s) {
//关键:回文,最长
int n = s.size();
//遍历肯定是遍历的,双指针?,指向一样再往中间靠拢?然后直接s.substr(从left开始,多少位)
//不是从外向内(判别回文串),是从内向外确定****
//两个中心、一个中心****
int max = 0 , start = 0;
auto expandAroundCenter =[&](int left , int right){
while(left >= 0 && right < n &&s[left] == s[right]){
left--;
right++;
}
int len = right - left - 1;
if(len > max){
start = left+1;
max = len;
}
};
for(int i = 0 ; i < n ; i++){
//确定回文串长度
//回文中心一个字符
expandAroundCenter(i,i);
//回文中心两个字符
expandAroundCenter(i,i+1);
}
return s.substr(start,max);
}
};
c++代码学习:lambda表达式
auto expandAroundCenter =[&](int left , int right){
while(left>=0 && right < n &&s[left] == s[right]){
left--;
right++;
}
int len = right-left-1;
if(max > len){
max = len;
start = left+1;//因为被left--了
}
};
524 Longest Word in Dictionary through Deleting
和522很类似isExit()和昨天的isSubsequence()是一样的—>子序列(字母相对位置一致即可)
class Solution {
public:
bool isExit(string str1, string str2){
//str2是否在str1中,和522一样,str2是否为str1的子序列
int n1 = str1.size(),n2 =str2.size();
if(n1 < n2) return false;
int s1 = 0 ,s2 = 0;
while(s1 < n1 && s2 <n2){
if (str1[s1] == str2[s2]) {
s2++;
}
s1++;
}
return s2 == n2;
}
string findLongestWord(string s, vector<string>& dictionary) {
//返回的是 dictionary中的字符串,这个字符串要可以被l中的消除掉
//最长 如果相等则返回字母序更小的,也就是当长度相等时不变就好了
string res = "";
int n = s.size();
for(string str:dictionary){
//str是否存在于dictionary中
if(isExit(s,str)){
if(res.size() < str.size() || (str.size() == res.size() && str < res)){
res = str;
}
}
}
return res;
}
};