字符串旋转:(例如 I am a student! 旋转为 student! a am I)
1.JAVA版
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(reverseString("I am a student!"));
}
//三步反转法
public static String reverseString(String str){
StringBuffer strBuf=new StringBuffer(str);
int from,to;
for(int i=0;i<strBuf.length();i++){
char tmp=strBuf.charAt(i);
if(tmp!=' '){
from=i;
for(;i<strBuf.length();i++){
tmp=strBuf.charAt(i);
if(tmp==' '){
to=i-1;
reverse(strBuf, from, to);//多次局部反转
break;
}
if(i==(strBuf.length()-1)){//一定要加,处理遍历到最后时 to未赋值的情况
reverse(strBuf, from, i);
}
}
}
}
strBuf.reverse();//整体反转
return strBuf.toString();
}
//反转从from到to
public static void reverse(StringBuffer strBuf,int from,int to){
while(from<to){
char tmp=strBuf.charAt(from);
strBuf.setCharAt(from++, strBuf.charAt(to));
strBuf.setCharAt(to--, tmp);
}
}
2.C++版
#include "stdafx.h"
#include <iostream>
using namespace std;
//蛮力移位法
void LeftShiftOne(char* s, int n);
void leftRotateString1(char* s, int n, int m);
//三步反转法
void ReverseString(char* s, int from, int to);
void leftRotateString2(char* s, int n, int m);
int main()
{
char str[] = "I am a student.";
int from, to;
int length = strlen(str);
for (int i = 0; i < length;i++) {
if (str[i]&&str[i]!=' ') {
from = i;
for (; i < length; i++) {
if (str[i] == ' ') {
to = i-1;
ReverseString(str,from,to);
break;
}
if (i==(length-1)) {
to = i;
ReverseString(str, from, to);
}
}
}
}
ReverseString(str,0, length-1);
cout << str;
cin >> from;
}
/*
字符串的旋转
*/
//---------------蛮力-------------------
//蛮力移位 时间复杂性O(mn)
void LeftShiftOne(char* s,int n) {
char tmp = s[0];//保存第一个字符
for (int i = 1; i < n;i++) {
s[i - 1] = s[i];
}
s[n - 1] = tmp;
}
//蛮力移m位
void leftRotateString1(char* s, int n, int m) {
for (int i=0;i<m;i++)
{
LeftShiftOne(s,n);
}
}
//-----------------三步翻转法-----------------
//将字符串s的from到to翻转
void ReverseString(char* s,int from,int to) {
while (from < to) {
char tmp = s[from];
s[from++] = s[to];
s[to--] = tmp;
}
}
void leftRotateString2(char* s,int n,int m) {
ReverseString(s,0,m-1);//1.旋转左半部
ReverseString(s, m, n - 1);//2.旋转右半部
ReverseString(s, 0, n - 1);//3.整体旋转
}