Skip to content

Commit eddf02e

Browse files
author
Kohei Asai
authored
557. Reverse Words in a String III (axross#127)
1 parent b3c15e9 commit eddf02e

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed
+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
// 557. Reverse Words in a String III
2+
// https://leetcode.com/problems/reverse-words-in-a-string-iii/
3+
export default function reverseWords(s: string): string {
4+
const chars = s.split("");
5+
6+
for (let i = 0, wordStart = 0; i <= chars.length; ++i) {
7+
if (s[i] !== " " && i < chars.length) continue;
8+
9+
for (let j = 0; j + wordStart < (wordStart + i) / 2; ++j) {
10+
[chars[j + wordStart], chars[i - j - 1]] = [
11+
chars[i - j - 1],
12+
chars[j + wordStart]
13+
];
14+
}
15+
16+
wordStart = i + 1;
17+
}
18+
19+
return chars.join("");
20+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import { test } from "https://deno.land/std/testing/mod.ts";
2+
import { assert } from "https://deno.land/std/testing/asserts.ts";
3+
import reverseWords from "./reverse_words_in_a_string_3.ts";
4+
5+
test("557. Reverse Words in a String III", () => {
6+
assert(
7+
reverseWords("Let's take LeetCode contest") ===
8+
"s'teL ekat edoCteeL tsetnoc"
9+
);
10+
});

0 commit comments

Comments
 (0)