Perform String Shifts
给一个string和一组数组shift, 0 表示左移, 1表示右移, 后边的数字表示移动的位数, 问结果如何. 先计算结果的移动方法, 然后再构建.
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 |
class Solution { public String stringShift(String str, int[][] shift) { int s = 0; for(int[] sh : shift) { if(sh[0] == 0){ s += sh[1]; } else{ s -= sh[1]; } } if(s == 0) return str; StringBuilder sb = new StringBuilder(str); if(s > 0) { for(int i = 0; i < s; i++) { char c = sb.charAt(0); sb.append(c); sb.deleteCharAt(0); } } else{ for(int i = s; i < 0; i++) { char c = sb.charAt(sb.length() - 1); sb.insert(0, c); sb.deleteCharAt(sb.length() - 1); } } return sb.toString(); } } |