LeetCode problem#2000
Reverse Prefix of Word
Solved in 1 languageJava
Solution
32 lines
1import java.util.Stack;
2
3class Solution {
4 // time O(n)
5 // space O(n)
6 public String reversePrefix(String word, char ch) {
7 Stack<Character> stack = new Stack<Character>();
8 boolean found = false;
9
10 for (int i = 0; i < word.length(); i++) {
11 stack.push(word.charAt(i));
12
13 if (word.charAt(i) == ch) {
14 found = true;
15 break;
16 }
17 }
18
19 if (!found) {
20 return word;
21 }
22
23 StringBuilder sb = new StringBuilder(word);
24 int j = 0;
25 while (!stack.isEmpty()) {
26 sb.setCharAt(j, stack.pop());
27 j++;
28 }
29
30 return sb.toString();
31 }
32}Want a walkthrough of this Java solution?
Get a step-by-step explanation of the idea behind the code.
Problem statements belong to LeetCode and are on leetcode.com. We're not affiliated with LeetCode.