题目:把一个字符串前面的若干个字符转移到字符串的尾部。
举个例子吧:输入字符串"abcdefg"
输出字符串"cdefgab"
这个题目和我在上一篇博客——翻转字符串,思路上是有关联的,都是通过翻转的方法,来得到需要的输出结果。
在这个题目中,翻转的条件和时机比较巧妙。
让我们先来观察一下吧——
那现在就可以按照这个思路来完成代码了——
java代码实现:(代码中会对一些函数或语句的功能进行注释)
package com.zyc.Q58_2;
/**
* Create with IntelliJ IDEA
* Author: zhouyichen
* Date:{2018/9/5}
* Time:{20:51}
*/
public class Method1 {
//函数Reverse的功能:翻转一段字符串
public void Reverse(char[] chars,int start,int end)
{
if(chars==null||chars.length<0||start<0||end>chars.length||start>end)
{
return;
}
while (start<end)
{
//首尾一一交换
char temp=chars[start];
chars[start]=chars[end];
chars[end]=temp;
start++;
end--;
}
}
//函数LeftRotateString的功能:并且控制翻转的范围(一共是三次翻转),每次分别调动Reverse函数;
public String LeftRotateString(String string,int n)
{
char[] data=string.toCharArray();
if(data!=null)
{
int total_lenght=data.length;
if(total_lenght>0&&n>0&&n<total_lenght)
{
//字符串前面的n个字符的首尾下标
int firstStart=0;
int firstEnd=n-1;
//字符串的后面部分字符的首尾下标
int secondStart=n;
int secondEnd=total_lenght-1;
//翻转字符串的前面n个字符
Reverse(data,0,n-1);
//翻转字符串的后面部分字符
Reverse(data,n,total_lenght-1);
//翻转整个字符串
Reverse(data,0,total_lenght-1);
}
}
//data是一个字符数组,在返回的时候要注意先转换成String类型的
return new String(data);
}
//主函数
public static void main(String[] args) {
String string="abcdefg";
System.out.println(new Method1().LeftRotateString(string,2));
}
}
控制台输出: