From decfe0c0b35147a5daf2c4a47bf2575a7501ee23 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Wed, 4 Dec 2024 00:28:01 +0100 Subject: [PATCH] =?UTF-8?q?java:=20add=20=C2=AB2109.=20Adding=20Spaces=20t?= =?UTF-8?q?o=20a=20String=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit URL: https://leetcode.com/problems/adding-spaces-to-a-string/ Signed-off-by: Matej Focko --- java/adding-space-to-a-string.java | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 java/adding-space-to-a-string.java diff --git a/java/adding-space-to-a-string.java b/java/adding-space-to-a-string.java new file mode 100644 index 0000000..ff545ec --- /dev/null +++ b/java/adding-space-to-a-string.java @@ -0,0 +1,18 @@ +class Solution { + public String addSpaces(String s, int[] spaces) { + var result = new StringBuilder(); + result.ensureCapacity(s.length() + spaces.length); + + int i = 0; + for (int j = 0; j < s.length(); ++j) { + if (i < spaces.length && spaces[i] == j) { + result.append(' '); + ++i; + } + + result.append(s.charAt(j)); + } + + return result.toString(); + } +}