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
  1. class Solution:
  2. def isCircularSentence(self, s: str) -> bool:
  3. if s[0]!=s[-1]:
  4. return False
  5. split=-1
  6. while True:
  7. split=s.find(' ', split+1)
  8. if split==-1:
  9. break
  10. if s[split-1]!=s[split+1]:
  11. return False
  12. return True


C++ 1-liner

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

沒有留言:

Related Posts Plugin for WordPress, Blogger...

熱門文章