微软算法100题26 左旋转字符串
26.左旋转字符串
题目:
定义字符串的左旋转操作:把字符串前面的若干个字符移动到字符串的尾部。
如把字符串abcdef 左旋转2 位得到字符串cdefab。请实现字符串左旋转的函数。
要求时间对长度为n 的字符串操作的复杂度为O(n),辅助内存为O(1)
思路:先反转整个字符串 -> fedcba 在分别反转各个子字符串 fedc - ba -> cdef - ab
1 package com.rui.microsoft; 2 3 public class Test26_LeftRotateString { 4 5 public static void main(String[] args) { 6 String s = leftRotate("abcdef", 5); 7 System.out.println(s); 8 } 9 10 public static String leftRotate(String s, int from){ 11 StringBuilder sb = new StringBuilder(); 12 13 //reverse all 14 s = reverse(s); 15 16 String s0 = s.substring(0, s.length() - from + 1); 17 String s1 = s.substring(s.length() - from + 1, s.length()); 18 19 //reverse each part 20 sb.append(reverse(s0)).append(reverse(s1)); 21 return sb.toString(); 22 } 23 24 private static String reverse(String s){ 25 char[] as = s.toCharArray(); 26 int i = 0; 27 int j = s.length() - 1; 28 while(i<j){ 29 swap(as, i,j); 30 i++; 31 j--; 32 } 33 return String.copyValueOf(as); 34 } 35 36 private static void swap(char[] a, int i, int j){ 37 char temp = a[i]; 38 a[i] = a[j]; 39 a[j] = temp; 40 } 41 }