LeetCode - Algorithms - 344. Reverse String

这题确实easy,做这题倒真可以脱离IDE在leetcode编辑器里刷题了。
做这题,又犯了一次java与js字符串的小错误,在Java里获取String长度的length()是method,在js里获取字符串长度的length是property,老是搞混淆了。

Javascript

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* @param {string} s
* @return {string}
*/
var reverseString = function(s) {
var r = "";
if (s!=null && s.length>0) {
for(var i=s.length-1;i>=0;i--) {
r+=s[i];
}
}
return r;
};

Submission Detail

  • 476 / 476 test cases passed.
  • Your runtime beats 96.31 % of javascript submissions.

Java

LOOP+SB

1

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public String reverseString(String s) {
StringBuilder sb = new StringBuilder();
if (s!=null && !s.isEmpty()) {
for(int i=s.length()-1;i>=0;i--) {
sb.append(s.charAt(i));
}
}
return sb.toString();
}
}

Submission Detail

  • 476 / 476 test cases passed.
  • Your runtime beats 13.87 % of java submissions.

跟js写法差不多,这java代码的性能倒不行

2

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public String reverseString(String s) {
StringBuilder sb = new StringBuilder();
if (s!=null && !s.isEmpty()) {
char[] arr = s.toCharArray();
for(int i=arr.length-1;i>=0;i--) {
sb.append(arr[i]);
}
}
return sb.toString();
}
}

Submission Detail

  • 476 / 476 test cases passed.
  • Your runtime beats 5.40 % of java submissions.

SB

1
2
3
4
5
6
7
8
9
10
class Solution {
public String reverseString(String s) {
String r = "";
if (s!=null && !s.isEmpty()) {
StringBuilder sb = new StringBuilder(s);
r = sb.reverse().toString();
}
return r;
}
}

Submission Detail

  • 476 / 476 test cases passed.
  • Your runtime beats 5.40 % of java submissions.

直接用StringBuilder的reverse(),用StringBuffer好像也类似,性能没什么变化

逆转字符数组

Ref

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public String reverseString(String s) {
String r = "";
if (s!=null && !s.isEmpty()) {
char[] arr = s.toCharArray();
for (int i=0; i<arr.length/2; i++) {
char temp = arr[i];
arr[i] = arr[arr.length-1-i];
arr[arr.length-1-i] = temp;
}
r = new String(arr);
}
return r;
}
}

Submission Detail

  • 476 / 476 test cases passed.
  • Your runtime beats 7.62 % of java submissions.

Rust

Rust 95%+

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
impl Solution {
pub fn reverse_string(s: &mut Vec<char>) {
let len = s.len();
if len > 0 {
let mut midpoint = len / 2;
if len % 2 != 0 {
midpoint += 1;
}
for i in 0..midpoint {
let j = len - i - 1;
let buffer = s[i];
s[i] = s[j];
s[j] = buffer;
}
}
}
}

Submission Detail

  • 478 / 478 test cases passed.
  • Runtime: 20 ms, faster than 95.94% of Rust online submissions for Reverse String.
  • Memory Usage: 5.1 MB, less than 100.00% of Rust online submissions for Reverse String.