码迷,mamicode.com
首页 > 其他好文 > 详细

Rotate String

时间:2016-07-06 09:57:05      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:

Given a string and an offset, rotate string by offset. (rotate from left to right)

Example

Given "abcdefg".

offset=0 => "abcdefg"
offset=1 => "gabcdef"
offset=2 => "fgabcde"
offset=3 => "efgabcd"

分析:
利用 (A^TB^T)^T = BA
 1 public class Solution {
 2     /**
 3      * @param str: an array of char
 4      * @param offset: an integer
 5      * @return: nothing
 6      */
 7     public void rotateString(char[] str, int offset) {
 8         if (str == null || str.length <= 1) return;
 9         offset = offset % str.length;
10         if (offset == 0) return;
11         
12         int p = str.length - 1 - offset;
13         
14         swapFromIToJ(str, 0, p);
15         swapFromIToJ(str, p + 1, str.length - 1);
16         swapFromIToJ(str, 0, str.length - 1);
17     }
18     
19     public void swapFromIToJ(char[] str, int i, int j) {
20         while (i < j) {
21             char temp = str[i];
22             str[i] = str[j];
23             str[j] = temp;
24             i++;
25             j--;
26         }
27     }
28 }

 



Rotate String

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5645642.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!