import java.util.*; public class Solution { public String trans(String s, int n) { // write code here if (s == null || s.length() < 1 || n < 1) { return s; } char[] arr = s.toCharArray(); reverse(arr, 0, n - 1); List<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) { if (arr[i] == ' ') { list.add(i); } } if (list.size() == 0) { reverse(arr, 0, n - 1); convert(arr, 0, n - 1); return new String(arr); } int l = 0; int r = 0; for (int i = 0; i < list.size(); i++) { if (i == 0 && list.get(i) == 0) { continue; } else if (i == 0 && list.get(i) != 0) { l = 0; } else { l = list.get(i - 1) + 1; } r = list.get(i) - 1; if (l != r) { reverse(arr, l, r); } convert(arr, l, r); } r = list.get(list.size() - 1); if (r != n - 1) { reverse(arr, r + 1, n - 1); convert(arr, r + 1, n - 1); } return new String(arr); } private void reverse(char[] arr, int l, int r) { while (l < r) { char tmp = arr[l]; arr[l] = arr[r]; arr[r] = tmp; l++; r--; } } private void convert(char[] arr, int l, int r) { for (int i = l; i <= r; i++) { if (Character.isLowerCase(arr[i])) { arr[i] = (char) (arr[i] - 'a' + 'A'); } else { arr[i] = (char) (arr[i] - 'A' + 'a'); } } } }