31
31
32
32
创建一个长度为 $26$ 的数组,统计每个字母出现的频率,至多有一个字符出现奇数次数即可。
33
33
34
- 时间复杂度 $O(n)$,空间复杂度 $O(26 )$。其中 $n$ 是字符串的长度。
34
+ 时间复杂度 $O(n)$,空间复杂度 $O(|\Sigma| )$。其中 $n$ 是字符串的长度,而 $|\Sigma|$ 是字符集的大小,本题中字符集为小写字母,因此 $|\Sigma|=26$ 。
35
35
36
36
** 方法二:哈希表**
37
37
38
38
利用哈希表来维护元素。遍历字符串每个字母 $s[ i] $,若 $s[ i] $ 在哈希表中,则将 $s[ i] $ 从哈希表中删除,否则将 $s[ i] $ 加入哈希表。
39
39
40
40
遍历结束,若哈希表中元素个数不超过 $1$,则返回 $true$,否则返回 $false$。
41
41
42
- 时间复杂度 $O(n)$,空间复杂度 $O(26 )$。其中 $n$ 是字符串的长度。
42
+ 时间复杂度 $O(n)$,空间复杂度 $O(|\Sigma| )$。其中 $n$ 是字符串的长度,而 $|\Sigma|$ 是字符集的大小,本题中字符集为小写字母,因此 $|\Sigma|=26$ 。
43
43
44
44
<!-- tabs:start -->
45
45
50
50
``` python
51
51
class Solution :
52
52
def canPermutePalindrome (self , s : str ) -> bool :
53
- return sum (v % 2 for v in Counter(s).values()) <= 1
53
+ return sum (v & 1 for v in Counter(s).values()) < 2
54
54
```
55
55
56
56
### ** Java**
@@ -64,11 +64,11 @@ class Solution {
64
64
for (char c : s. toCharArray()) {
65
65
++ cnt[c - ' a' ];
66
66
}
67
- int n = 0 ;
68
- for (int v : cnt) {
69
- n += v % 2 ;
67
+ int odd = 0 ;
68
+ for (int x : cnt) {
69
+ odd += x & 1 ;
70
70
}
71
- return n < 2 ;
71
+ return odd < 2 ;
72
72
}
73
73
}
74
74
```
@@ -80,10 +80,14 @@ class Solution {
80
80
public:
81
81
bool canPermutePalindrome(string s) {
82
82
vector<int > cnt(26);
83
- for (char& c : s) ++cnt[ c - 'a'] ;
84
- int n = 0;
85
- for (int& v : cnt) n += v & 1;
86
- return n < 2;
83
+ for (char& c : s) {
84
+ ++cnt[ c - 'a'] ;
85
+ }
86
+ int odd = 0;
87
+ for (int x : cnt) {
88
+ odd += x & 1;
89
+ }
90
+ return odd < 2;
87
91
}
88
92
};
89
93
```
@@ -92,15 +96,27 @@ public:
92
96
93
97
```go
94
98
func canPermutePalindrome(s string) bool {
95
- cnt := make([ ]int, 26)
99
+ cnt := [26 ]int{}
96
100
for _, c := range s {
97
101
cnt[c-'a']++
98
102
}
99
- n := 0
100
- for _, v := range cnt {
101
- n += v & 1
103
+ odd := 0
104
+ for _, x := range cnt {
105
+ odd += x & 1
102
106
}
103
- return n < 2
107
+ return odd < 2
108
+ }
109
+ ```
110
+
111
+ ### ** TypeScript**
112
+
113
+ ``` ts
114
+ function canPermutePalindrome(s : string ): boolean {
115
+ const cnt: number [] = new Array (26 ).fill (0 );
116
+ for (const c of s ) {
117
+ ++ cnt [c .charCodeAt (0 ) - 97 ];
118
+ }
119
+ return cnt .filter (c => c % 2 === 1 ).length < 2 ;
104
120
}
105
121
```
106
122
@@ -112,15 +128,11 @@ func canPermutePalindrome(s string) bool {
112
128
* @return {boolean}
113
129
*/
114
130
var canPermutePalindrome = function (s ) {
115
- let ss = new Set ();
116
- for (let c of s) {
117
- if (ss .has (c)) {
118
- ss .delete (c);
119
- } else {
120
- ss .add (c);
121
- }
131
+ const cnt = new Array (26 ).fill (0 );
132
+ for (const c of s) {
133
+ ++ cnt[c .charCodeAt () - ' a' .charCodeAt ()];
122
134
}
123
- return ss . size < 2 ;
135
+ return cnt . filter ( c => c % 2 === 1 ). length < 2 ;
124
136
};
125
137
```
126
138
0 commit comments