File tree 4 files changed +26
-12
lines changed
solution/1300-1399/1374.Generate a String With Characters That Have Odd Counts
4 files changed +26
-12
lines changed Original file line number Diff line number Diff line change 44
44
45
45
<!-- 这里可写通用的实现逻辑 -->
46
46
47
+ ** 方法一:构造**
48
+
49
+ 如果 $n$ 为奇数,那么直接构造 $n$ 个 ` 'a' ` 即可。
50
+
51
+ 如果 $n$ 为偶数,那么构造 $n-1$ 个 ` 'a' ` 和 $1$ 个 ` 'b' ` 即可。
52
+
53
+ 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为字符串长度。
54
+
47
55
<!-- tabs:start -->
48
56
49
57
### ** Python3**
@@ -75,7 +83,9 @@ class Solution {
75
83
public:
76
84
string generateTheString(int n) {
77
85
string ans(n, 'a');
78
- if (n % 2 == 0) ans[ 0] = 'b';
86
+ if (n % 2 == 0) {
87
+ ans[ 0] = 'b';
88
+ }
79
89
return ans;
80
90
}
81
91
};
@@ -99,11 +109,11 @@ func generateTheString(n int) string {
99
109
100
110
``` ts
101
111
function generateTheString(n : number ): string {
102
- const res = new Array (n ).fill (' a' );
112
+ const ans = Array (n ).fill (' a' );
103
113
if (n % 2 === 0 ) {
104
- res [ n - 1 ] = ' b' ;
114
+ ans [ 0 ] = ' b' ;
105
115
}
106
- return res .join (' ' );
116
+ return ans .join (' ' );
107
117
}
108
118
```
109
119
Original file line number Diff line number Diff line change @@ -68,7 +68,9 @@ class Solution {
68
68
public:
69
69
string generateTheString(int n) {
70
70
string ans(n, 'a');
71
- if (n % 2 == 0) ans[ 0] = 'b';
71
+ if (n % 2 == 0) {
72
+ ans[ 0] = 'b';
73
+ }
72
74
return ans;
73
75
}
74
76
};
@@ -92,11 +94,11 @@ func generateTheString(n int) string {
92
94
93
95
``` ts
94
96
function generateTheString(n : number ): string {
95
- const res = new Array (n ).fill (' a' );
97
+ const ans = Array (n ).fill (' a' );
96
98
if (n % 2 === 0 ) {
97
- res [ n - 1 ] = ' b' ;
99
+ ans [ 0 ] = ' b' ;
98
100
}
99
- return res .join (' ' );
101
+ return ans .join (' ' );
100
102
}
101
103
```
102
104
Original file line number Diff line number Diff line change @@ -2,7 +2,9 @@ class Solution {
2
2
public:
3
3
string generateTheString (int n) {
4
4
string ans (n, ' a' );
5
- if (n % 2 == 0 ) ans[0 ] = ' b' ;
5
+ if (n % 2 == 0 ) {
6
+ ans[0 ] = ' b' ;
7
+ }
6
8
return ans;
7
9
}
8
10
};
Original file line number Diff line number Diff line change 1
1
function generateTheString ( n : number ) : string {
2
- const res = new Array ( n ) . fill ( 'a' ) ;
2
+ const ans = Array ( n ) . fill ( 'a' ) ;
3
3
if ( n % 2 === 0 ) {
4
- res [ n - 1 ] = 'b' ;
4
+ ans [ 0 ] = 'b' ;
5
5
}
6
- return res . join ( '' ) ;
6
+ return ans . join ( '' ) ;
7
7
}
You can’t perform that action at this time.
0 commit comments