雙指針

最長子序列

524. Longest Word in Dictionary through Deleting (Medium)

Input:
s = "abpcplea", d = ["ale","apple","monkey","plea"]

Output:
"apple"

題目描述:刪除 s 中的一些字符,使得它構成字符串列表 d 中的一個字符串,找出能構成的最長字符串。如果有多個相同長度的結果,返回字典序的最小字符串。

class Solution {
public:
    string findLongestWord(string s, vector<string>& d) {
        sort(d.begin(), d.end(), [](string a, string b){
            if (a.size() == b.size()) return a < b;
            return a.size() > b.size();
        });
        for (string str : d) {
            int i = 0;
            for (char c : s) {
                if (i < str.size() && c == str[i]) ++i;
            }
            if (i == str.size()) return str;
        }
        return "";
    }
};

裏面的sort的格式很神奇 一般是放一個bool函數 這裏很神奇  一般情況

這裏的a.size()>b.size()表明是從大到小排列 ,然後中間的if語句不清楚,難道表明當相等的時候按照a小來判斷??

class Solution {
public:
    string findLongestWord(string s, vector<string>& d) {
        string res = "";
        for (string str : d) {
            int i = 0;
            for (char c : s) {
                if (i < str.size() && c == str[i]) ++i;
            }
            if (i == str.size() && str.size() >= res.size()) {
                if (str.size() > res.size() || str < res) {
                    res = str;
                }
            }
        }
        return res;
    }
};

不用sort了 直接算 不過兩個string直接str<res這樣對比可以嗎????

平方數之和

633  給定一個非負整數 c ,你要判斷是否存在兩個整數 a 和 b,使得 a2 + b2 = c。

class Solution {
public:
    bool judgeSquareSum(int c) {
        unsigned int a = 0, b = sqrt(c);
        while (a <= b) {
            if (a * a + b * b == c) return true;
            else if (a * a + b * b < c) ++a;
            else --b;
        }
        return false;
    }
};

剛開始怎麼都不滿足要求 加了一個unsigned就好啦!

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章