vector rotation problem

编程珠玑上的一道题目:将一个具有n个元素的一位向量向左旋转i个位置,

例如n=8,i=3,字符串“abcdefgh”转换为“defghabc”

思路一:考虑空间复杂度的情况下,利用临时变量t分别存放a、b、c,每次将剩下的defgh向前移动1位,再把abc依次放在字符串最后

思路二:书中给出了更好的方法,先把字符串abc看作a,把defgh看作b,所以原字符串为ab,翻转后为ba,步骤如下:

java实现:

 1 /**
 2  * Created by hogarth on 2016/5/3.
 3  * A problem from programming pearls
 4  * Rotate String "abcdfefgh" to "defghabc"
 5  * Solution: AB->ArB->ArBr->(ArBr)r->BA
 6  */
 7 import java.util.*;
 8 
 9 public class vector_rotation {
10     public static void main(String[] args) {
11         Partition p = new Partition();
12         String s = "abcdefgh";
13         System.out.println("before:"+ s + " after:" + p.rotate(s,3));
14     }
15 
16     public static class Partition {
17         public String rotate(String s, int i) {
18             char[] c = s.toCharArray();
19             int length = c.length;
20             reverse(c, 0, i-1);
21             reverse(c, i, length-1);
22             reverse(c, 0, length-1);
23 
24             return String.valueOf(c);
25         }
26 
27         public void reverse(char[] c, int first, int last){
28             for (int j = 0; j < len/2; j++){
29                 char tmp = c[first+j];
30                 c[first+j] = c[last-j];
31                 c[last-j] = tmp;
32             }
33         }
34     }
35 }
1 输出:before:abcdefgh after:defhgabc

 

posted on 2016-05-03 18:01  hogarth  阅读(75)  评论(0)    收藏  举报

导航