Um momento
Leetcode / reverse-prefix-of-word

Pick a programming language:

Here is the source code for the solution to this problem.

import java.util.Stack;

class Solution {
    // time O(n)
    // space O(n)
    public String reversePrefix(String word, char ch) {
        Stack<Character> stack = new Stack<Character>();
        boolean found = false;

        for (int i = 0; i < word.length(); i++) {
            stack.push(word.charAt(i));

            if (word.charAt(i) == ch) {
                found = true;
                break;
            }
        }

        if (!found) {
            return word;
        }

        StringBuilder sb = new StringBuilder(word);
        int j = 0;
        while (!stack.isEmpty()) {
            sb.setCharAt(j, stack.pop());
            j++;
        }

        return sb.toString();
    }
}
Gostou da aula? 😆👍
Apoie nosso trabalho com uma doação: