- 有效的字母異位詞
class Solution {
public:
bool isAnagram(string s, string t) {
if(s.size()!=t.size())
return false;
int ans[26]={0};
for(auto& ch:s){
++ans[ch-'a'];
}
for(auto& ch:t){
--ans[ch-'a'];
}
return all_of(ans,ans+26,[](int i){return i==0;});
}
};
C++11 中提供了一些用于檢查序列中元素的演算法,包括:
-
all_of: 檢查序列中是否所有元素都滿足某個條件,
-
any_of: 檢查序列中是否存在至少一個元素滿足某個條件,
-
none_of: 檢查序列中是否不存在任何一個元素滿足某個條件,
這些演算法的使用方式如下:#include <algorithm> #include <array> int main() { std::array<int, 5> arr {1, 2, 3, 4, 5}; // 檢查陣列中是否所有元素都大于0 bool all_greater_than_zero = std::all_of(arr.begin(), arr.end(), [](int i) {return i > 0;}); // true // 檢查陣列中是否存在大于3的元素 bool any_greater_than_three = std::any_of(arr.begin(), arr.end(), [](int i) {return i > 3;}); // true // 檢查陣列中是否不存在大于10的元素 bool none_greater_than_ten = std::none_of(arr.begin(), arr.end(), [](int i) {return i > 10;}); // true }
這些演算法使用,只需要傳入序列的首尾迭代器和一個用于檢查條件的函式物件(上例使用了lambda運算式),然后演算法會對整個序列中的每個元素呼叫該函式物件,并根據回傳值判斷序列是否滿足條件,
這些演算法對檢查序列中元素很有用,可以使代碼更加簡潔明了,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/553797.html
標籤:C++
下一篇:返回列表