题目
类型:双指针
解题思路
先从前往后遍历,找到第一个 ch 的下标 idx(初始值为 -1),然后对 [0, idx] 应用双指针进行翻转(若没有 ch 字符,则 idx = -1,则 [0, idx] 为不合法区间,翻转过程被跳过)。
代码
class Solution {public String reversePrefix(String word, char ch) {int index = word.indexOf(ch);if (index >= 0) {char[] arr = word.toCharArray();int left = 0, right = index;while (left < right) {char temp = arr[left];arr[left] = arr[right];arr[right] = temp;left++;right--;}word = new String(arr);}return word;}}
