herrDeng網內搜尋

自訂搜尋

Ads

2024年11月2日 星期六

Python C++使用字串find迴圈速解Leetcode 2490 Circular Sentence


Python C++使用字串find迴圈速解Leetcode 2490  Circular Sentence
C++ & Python都有字串的find,用法都類似
split=s.find(' ', split+1)能找到s從index=split+1開始出現' '的第一個的index
[Python解請進, C++ 一行解]
-----
C++ & Python both have string find, and their usage is similar.
split=s.find(' ', split+1) can find the first index where ' ' appears in s starting from index=split+1
class Solution:
    def isCircularSentence(self, s: str) -> bool:
        if s[0]!=s[-1]: 
            return False
        split=-1
        while True:
            split=s.find(' ', split+1)
            if split==-1: 
                break
            if s[split-1]!=s[split+1]: 
                return False
        return True


C++ 1-liner

class Solution {
public:
    bool isCircularSentence(string& s) {
        return s[0]==s.back() && all_of(s.begin(), s.end(), [&, i=0](auto _) mutable{
            return !i++|| s[i]!=' ' || s[i-1]==s[i+1];
        });
    }
};

沒有留言:

Related Posts Plugin for WordPress, Blogger...

熱門文章