机械专业的菜狗初步刷力扣,基础知识都忘了,开始捡起代码转码,希望每天刷一道力扣,不管做没做对,都看看思路和语法。
方法一:两重循环枚举
思路与算法
class Solution {
public:
int maximumNumberOfStringPairs(vector<string>& words) {
int n = words.size();
int ans = 0;
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
if (words[i][0] == words[j][1] && words[i][1] == words[j][0]) {
++ans;
}
}
}
return ans;
}
};
作者:力扣官方题解
链接:https://leetcode.cn/problems/find-maximum-number-of-string-pairs/solutions/2604698/zui-da-zi-fu-chuan-pei-dui-shu-mu-by-lee-0x0e/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
class Solution:
def maximumNumberOfStringPairs(self, words: List[str]) -> int:
n = len(words)
ans = 0
for i in range(n):
for j in range(i + 1, n):
if words[i] == words[j][::-1]:
ans += 1
return ans
作者:力扣官方题解
链接:https://leetcode.cn/problems/find-maximum-number-of-string-pairs/solutions/2604698/zui-da-zi-fu-chuan-pei-dui-shu-mu-by-lee-0x0e/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
方法二哈希表
class Solution {
public:
int maximumNumberOfStringPairs(vector<string>& words) {
int n = words.size();
int ans = 0;
unordered_set<int> seen;
for (int i = 0; i < n; ++i) {
if (seen.count(words[i][1] * 100 + words[i][0])) {
++ans;
}
seen.insert(words[i][0] * 100 + words[i][1]);
}
return ans;
}
};
作者:力扣官方题解
链接:https://leetcode.cn/problems/find-maximum-number-of-string-pairs/solutions/2604698/zui-da-zi-fu-chuan-pei-dui-shu-mu-by-lee-0x0e/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
class Solution:
def maximumNumberOfStringPairs(self, words: List[str]) -> int:
ans = 0
seen = set()
for i, word in enumerate(words):
if word[::-1] in seen:
ans += 1
seen.add(word)
return ans
作者:力扣官方题解
链接:https://leetcode.cn/problems/find-maximum-number-of-string-pairs/solutions/2604698/zui-da-zi-fu-chuan-pei-dui-shu-mu-by-lee-0x0e/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。