LC.P2744[最大字符串配对数目]

方法一:哈希表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public int maximumNumberOfStringPairs(String[] words) {
int ans = 0;
boolean[][] visited = new boolean[26][26];
for (String word : words) {
int x = word.charAt(0) - 'a', y = word.charAt(1) - 'a';
if (visited[y][x]){
++ans;
} else {
visited[x][y] = true;
}
}
return ans;
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(n)$