字符串循环左移N位

/**
 * 将一个字符串中的子串左移n位
 * 要求时间复杂度为o(n),空间复杂度为o(1)
 * @author 
 *
 */
public class LeftShiftNString {

/**
* 反转字符数组
* @param s 字符数组
* @param from 起始字符
* @param to 截止字符
*/
private static void reverseString(char[]s,int from,int to)
{
while(from<to)
{
char t=s[from];
s[from++]=s[to];
s[to--]=t;
}
}

/**

* @param s 要左移的字符数组
* @param n 字符数组长度
* @param m 循环左移m位
*/
private static void leftRotateString(char[]s,int n,int m)
{
m %=n; //左移位数超过字符数组长度
reverseString(s, 0,m-1);
reverseString(s, m, n-1);
reverseString(s, 0, n-1);
}

public static void main(String[] args) {
char[]s={'a','b','c','d','e'};
// reverseString(s, 0, 3);
leftRotateString(s, s.length, 6);
for(char c:s)
{
System.out.println(c);
}
}
}

猜你喜欢

转载自blog.csdn.net/u013230189/article/details/80070927
今日推荐