Lintcode: Rotate String

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

Example
Given "abcdefg"

for offset=0, return "abcdefg"

for offset=1, return "gabcdef"

for offset=2, return "fgabcde"

for offset=3, return "efgabcd"

需要注意的是:if (A.length == 0) return new char[0]; 空数组

 1 public class Solution {
 2     /*
 3      * param A: A string
 4      * param offset: Rotate string with offset.
 5      * return: Rotated string.
 6      */
 7     public char[] rotateString(char[] A, int offset) {
 8         // wirte your code here
 9         if (A==null || A.length == 0) return new char[0];
10         String str = new String(A);
11         offset %= str.length();
12         if (offset == 0) return str.toCharArray();
13         String first = str.substring(0, str.length()-offset);
14         String second = str.substring(str.length()-offset);
15         String res = second + first;
16         return res.toCharArray();
17     }
18 };

 法二(推荐):

 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         // write your code here
 9         if (str==null || str.length==0) return;
10         offset %= str.length;
11         if (offset == 0) return;
12         reverse(str, 0, str.length-1);
13         reverse(str, 0, offset-1);
14         reverse(str, offset, str.length-1);
15     }
16     
17     public void reverse(char[] str, int l, int r) {
18         
19         while (l < r) {
20             char temp = str[l];
21             str[l] = str[r];
22             str[r] = temp;
23             l++;
24             r--;
25         }
26     }
27 }

 

转载于:https://www.cnblogs.com/EdwardLiu/p/4427493.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值