File tree 4 files changed +53
-31
lines changed
solution/0300-0399/0344.Reverse String
4 files changed +53
-31
lines changed Original file line number Diff line number Diff line change 35
35
<!-- 这里可写当前语言的特殊实现逻辑 -->
36
36
37
37
``` python
38
-
38
+ class Solution :
39
+ def reverseString (self , s : List[str ]) -> None :
40
+ """
41
+ Do not return anything, modify s in-place instead.
42
+ """
43
+ s[:] = s[::- 1 ]
39
44
```
40
45
41
46
### ** Java**
42
47
43
48
<!-- 这里可写当前语言的特殊实现逻辑 -->
44
49
45
50
``` java
46
-
51
+ class Solution {
52
+ public void reverseString (char [] s ) {
53
+ int n;
54
+ if (s == null || (n = s. length) < 2 ) return ;
55
+ int i = 0 , j = n - 1 ;
56
+ while (i < j) {
57
+ char t = s[i];
58
+ s[i] = s[j];
59
+ s[j] = t;
60
+ ++ i;
61
+ -- j;
62
+ }
63
+ }
64
+ }
47
65
```
48
66
49
67
### ** ...**
Original file line number Diff line number Diff line change 47
47
### ** Python3**
48
48
49
49
``` python
50
-
50
+ class Solution :
51
+ def reverseString (self , s : List[str ]) -> None :
52
+ """
53
+ Do not return anything, modify s in-place instead.
54
+ """
55
+ s[:] = s[::- 1 ]
51
56
```
52
57
53
58
### ** Java**
54
59
55
60
``` java
56
-
61
+ class Solution {
62
+ public void reverseString (char [] s ) {
63
+ int n;
64
+ if (s == null || (n = s. length) < 2 ) return ;
65
+ int i = 0 , j = n - 1 ;
66
+ while (i < j) {
67
+ char t = s[i];
68
+ s[i] = s[j];
69
+ s[j] = t;
70
+ ++ i;
71
+ -- j;
72
+ }
73
+ }
74
+ }
57
75
```
58
76
59
77
### ** ...**
Original file line number Diff line number Diff line change 1
1
class Solution {
2
- public String reverseString (String s ) {
3
- if (s == null || s .length () < 2 ) {
4
- return s ;
2
+ public void reverseString (char [] s ) {
3
+ int n ;
4
+ if (s == null || (n = s .length ) < 2 ) return ;
5
+ int i = 0 , j = n - 1 ;
6
+ while (i < j ) {
7
+ char t = s [i ];
8
+ s [i ] = s [j ];
9
+ s [j ] = t ;
10
+ ++i ;
11
+ --j ;
5
12
}
6
- char [] chars = s .toCharArray ();
7
- int p = 0 ;
8
- int q = chars .length - 1 ;
9
- while (p < q ) {
10
- char tmp = chars [p ];
11
- chars [p ] = chars [q ];
12
- chars [q ] = tmp ;
13
- ++p ;
14
- --q ;
15
- }
16
- return String .valueOf (chars );
17
13
}
18
-
19
14
}
Original file line number Diff line number Diff line change 1
1
class Solution :
2
- def reverseString (self , s ) :
2
+ def reverseString (self , s : List [ str ]) -> None :
3
3
"""
4
- :type s: str
5
- :rtype: str
4
+ Do not return anything, modify s in-place instead.
6
5
"""
7
- length = len (s )
8
- if length < 2 :
9
- return s
10
- ns = ''
11
- p = length - 1
12
- while p >= 0 :
13
- ns += s [p ]
14
- p -= 1
15
- return ns
6
+ s [:] = s [::- 1 ]
You can’t perform that action at this time.
0 commit comments