# 反转单词前缀

import java.util.PriorityQueue;
import java.util.Stack;

/**
 * @author your name
 * @date 上午10:03
 * @Desc the description of this class
 **/
class Solution2000 {
    public static void main(String[] args) {
        System.out.println(new Solution2000().reversePrefix("abcdefd", 'd'));
    }

    public String reversePrefix_Old(String word, char ch) {
        Stack<Character> stack = new Stack<>();
        int flag = -1;
        for (int i = 0; i < word.length(); i++) {
            stack.push(word.charAt(i));
            if (word.charAt(i) == ch) {
                flag = i + 1;
                break;
            }
        }
        if (flag == -1) {
            return word;
        }
        StringBuilder res = new StringBuilder();
        while (!stack.isEmpty()) {
            res.append(stack.pop());
        }
        res.append(word.substring(flag));
        return res.toString();
    }

    public String reversePrefix(String word, char ch) {
        int index = word.indexOf(ch);
        if (index != -1) {
            char[] chars = word.toCharArray();
            int left = 0;
            int right = index;
            while (left < right) {
                char temp = chars[left];
                chars[left] = chars[right];
                chars[right] = temp;
                left++;
                right--;
            }
            word = new String(chars);
        }
        return word;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52