【题目】对于一个给定的字符序列S,旋转指定位置左边的字符到右边.。
* 例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。
* 【思路】先分成两个部分:abc XYZdef,再每个部分反转cba fedZYX,再整个句子反转XYZdef abc
1 package com.exe9.offer; 2 3 /** 4 * 【题目】对于一个给定的字符序列S,旋转指定位置左边的字符到右边.。 5 * 例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。 6 * 【思路】先分成两个部分:abc XYZdef,再每个部分反转cba fedZYX,再整个句子反转XYZdef abc 7 * @author WGS 8 * 9 */ 10 public class LeftRotateString { 11 12 public void Reverse(char[] str,int begin,int end){ 13 if(str==null || str.length<=0) return ; 14 while(begin<=end){ 15 char temp=str[begin]; 16 str[begin]=str[end]; 17 str[end]=temp; 18 end--; 19 begin++; 20 } 21 } 22 23 public String getLeftRotateString(String str,int n){ 24 if(str==null || str.length()<=0 ||n>=str.length() ||n<0) return str; 25 int len=str.length(); 26 char[] charStr=str.toCharArray(); 27 //分成4个部分 28 int firstBegin=0; 29 int firstEnd=n-1; 30 int secondBegin=n; 31 int secondEnd=len-1; 32 33 //反转每个部分的单词 34 Reverse(charStr, firstBegin, firstEnd); 35 Reverse(charStr, secondBegin, secondEnd); 36 //反转整个句子 37 Reverse(charStr, firstBegin, secondEnd); 38 39 return new String(charStr); 40 41 } 42 public static void main(String[] args) { 43 LeftRotateString left=new LeftRotateString(); 44 String str="abcdefg";//cdefg sab 45 String str2=left.getLeftRotateString(str, 5); 46 System.out.println(str2); 47 } 48 }

浙公网安备 33010602011771号