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]; 空数组

 public class Solution {
/*
* param A: A string
* param offset: Rotate string with offset.
* return: Rotated string.
*/
public char[] rotateString(char[] A, int offset) {
// wirte your code here
if (A==null || A.length == 0) return new char[0];
String str = new String(A);
offset %= str.length();
if (offset == 0) return str.toCharArray();
String first = str.substring(0, str.length()-offset);
String second = str.substring(str.length()-offset);
String res = second + first;
return res.toCharArray();
}
};

法二(推荐):

 public class Solution {
/**
* @param str: an array of char
* @param offset: an integer
* @return: nothing
*/
public void rotateString(char[] str, int offset) {
// write your code here
if (str==null || str.length==0) return;
offset %= str.length;
if (offset == 0) return;
reverse(str, 0, str.length-1);
reverse(str, 0, offset-1);
reverse(str, offset, str.length-1);
} public void reverse(char[] str, int l, int r) { while (l < r) {
char temp = str[l];
str[l] = str[r];
str[r] = temp;
l++;
r--;
}
}
}
上一篇:NSArray或NSDictionary中汉字输出


下一篇:Windows Performance Monitoring with perfmon