From 0cda241a7e6226b1c86e15efc8d7a9c6200f9cfd Mon Sep 17 00:00:00 2001 From: Kohei Asai Date: Mon, 7 Oct 2019 14:54:49 -0700 Subject: [PATCH] 557. Reverse Words in a String III --- solutions/reverse_words_in_a_string_3.ts | 20 +++++++++++++++++++ solutions/reverse_words_in_a_string_3_test.ts | 10 ++++++++++ 2 files changed, 30 insertions(+) create mode 100644 solutions/reverse_words_in_a_string_3.ts create mode 100644 solutions/reverse_words_in_a_string_3_test.ts diff --git a/solutions/reverse_words_in_a_string_3.ts b/solutions/reverse_words_in_a_string_3.ts new file mode 100644 index 0000000..76c17f0 --- /dev/null +++ b/solutions/reverse_words_in_a_string_3.ts @@ -0,0 +1,20 @@ +// 557. Reverse Words in a String III +// https://leetcode.com/problems/reverse-words-in-a-string-iii/ +export default function reverseWords(s: string): string { + const chars = s.split(""); + + for (let i = 0, wordStart = 0; i <= chars.length; ++i) { + if (s[i] !== " " && i < chars.length) continue; + + for (let j = 0; j + wordStart < (wordStart + i) / 2; ++j) { + [chars[j + wordStart], chars[i - j - 1]] = [ + chars[i - j - 1], + chars[j + wordStart] + ]; + } + + wordStart = i + 1; + } + + return chars.join(""); +} diff --git a/solutions/reverse_words_in_a_string_3_test.ts b/solutions/reverse_words_in_a_string_3_test.ts new file mode 100644 index 0000000..bbf71f5 --- /dev/null +++ b/solutions/reverse_words_in_a_string_3_test.ts @@ -0,0 +1,10 @@ +import { test } from "https://deno.land/std/testing/mod.ts"; +import { assert } from "https://deno.land/std/testing/asserts.ts"; +import reverseWords from "./reverse_words_in_a_string_3.ts"; + +test("557. Reverse Words in a String III", () => { + assert( + reverseWords("Let's take LeetCode contest") === + "s'teL ekat edoCteeL tsetnoc" + ); +});