问题描述:
给定字符串和左旋的字符数,写程序实现字符串的左旋操作。例如对于字符串”12345678″, 左旋转4个字符后,变成”56781234″。要求时间复杂度为O(n),空间复杂度O(1)。
问题分析:
假设字符串表示为XY,X表示需要左旋的部分,左旋后字符串表示为YX。
代码实现:
package oschina.IT100;
/**
* @project: oschina
* @filename: IT26.java
* @version: 0.10
* @author: JM Han
* @date: 5:23 PM 1/5/2016
* @comment: Rotate characters of a String
* @result: After rotate 3 of 12345678 is: 45678123
*/
public class IT26 {
public static String rotateString(String s, int n){
StringBuilder sxb = new StringBuilder(s.substring(0, n));
StringBuilder syb = new StringBuilder(s.substring(n));
StringBuilder srb = sxb.reverse().append(syb.reverse());
return srb.reverse().toString();
}
public static void main(String[] args) {
String src = "12345678"; int n = 3;
System.out.println("After rotate " + n + "character of " + src + " is: " + rotateString(src, n));
}
}
来源:oschina
链接:https://my.oschina.net/u/2356166/blog/597877