【微软100题】定义字符串的左旋转操作:把字符串前面的若干个字符移动到字符串的尾部。 如把字符串abcdef左旋转2位得到字符串cdefab。请实现字符串左旋转的函数。

package test;

/**
 * 定义字符串的左旋转操作:把字符串前面的若干个字符移动到字符串的尾部。 如把字符串abcdef左旋转2位得到字符串cdefab。

请实现字符串左旋转的函数。 * 要求时间对长度为n的字符串操作的复杂度为O(n),辅助内存为O(1)。 * * @author Zealot * */ public class MS_26 { private void rotateString(String s, int rotate) { System.out.println("翻转前的字符串"+s); char temp; char[] c = s.toCharArray(); for(int i = 0, j = rotate - 1; i < j; i++, j--) { temp = c[i]; c[i] = c[j]; c[j] = temp; } for(int i = rotate, j=c.length - 1; i < j; i++,j--){ temp = c[i]; c[i] = c[j]; c[j] = temp; } for(int i = 0, j=c.length - 1; i < j; i++,j--){ temp = c[i]; c[i] = c[j]; c[j] = temp; } /*for(int i =0 ; i < c.length; i++) { System.out.print(c[i]); }*/ System.out.println("翻转后的字符串"+String.valueOf(c)); } public static void main(String[] args) { int rotate=2; String s = "abcdef"; MS_26 ms26 = new MS_26(); ms26.rotateString(s, rotate); } }


原文地址:https://www.cnblogs.com/gcczhongduan/p/5344576.html