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;
    }
};
posted @ 2024-03-24 18:27  想成为编程高手的阿曼  阅读(2)  评论(0编辑  收藏  举报