二刷 06/2022
Version #1 Char array in-place reverse
Time O(N)
Space O(N)
Runtime: 5 ms, faster than 91.68% of Java online submissions for Reverse Words in a String III.
Memory Usage: 48.8 MB, less than 75.85% of Java online submissions for Reverse Words in a String III.
class Solution {
public String reverseWords(String s) {
// s f
// abc def
char[] chars = s.toCharArray();
int slow = 0, fast = 0;
while (fast <= chars.length) {
if (fast == chars.length || chars[fast] == ' ') {
reverse(chars, slow, fast - 1);
slow = fast + 1;
}
fast++;
}
return new String(chars);
}
private void reverse(char[] chars, int start, int end) {
while (start < end) {
char c = chars[start];
chars[start] = chars[end];
chars[end] = c;
start++;
end--;
}
}
}
Version #2 StringBuilder reverse function
Time O(N)
Space O(N)
Runtime: 4 ms, faster than 96.93% of Java online submissions for Reverse Words in a String III.
Memory Usage: 42.9 MB, less than 87.56% of Java online submissions for Reverse Words in a String III.
class Solution {
public String reverseWords(String s) {
String[] parts = s.split(" ");
StringBuilder sb = new StringBuilder();
for (String part : parts) {
sb.append(new StringBuilder(part).reverse().toString());
sb.append(" ");
}
return sb.toString().trim();
}
}
40.36 %
class Solution {
public String reverseWords(String s) {
if (s == null || s.length() == 0) {
return s;
}
String[] strs = s.split("\\s+");
StringBuilder sb = new StringBuilder();
for (String str : strs) {
sb.append(" ").append(reverse(str));
}
return sb.length() == 0 ? "" : sb.substring(1).toString();
}
private String reverse(String str) {
char[] chars = str.toCharArray();
int left = 0;
int right = chars.length - 1;
while (left < right) {
char temp = chars[left];
chars[left] = chars[right];
chars[right] = temp;
left++;
right--;
}
return new String(chars);
}
}
No comments:
Post a Comment