LeetCode刷题记录——day6
1、https://leetcode.cn/problems/length-of-last-word/description/?envType=study-plan-v2&envId=top-interview-150
直接从后往前遍历就好
class Solution {
public:
int lengthOfLastWord(string s) {
int length=0;
int len=s.length();
for(int i=len-1;i>=0;i--){
if(s[i]!=' '){
length++;
}
if(s[i]==' '&&length>0){
break;
}
}
return length;
}
};
2、https://leetcode.cn/problems/longest-common-prefix/?envType=study-plan-v2&envId=top-interview-150
简单遍历就好
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
char falg_s;
string ans;
for(int i=0;i<strs[0].length();i++){
falg_s=strs[0][i];
for(int j=1;j<strs.size();j++){
if(strs[j][i]!=falg_s||i>strs[j].length()){
return ans;
}
}
ans=ans+falg_s;
}
return ans;
}
};