LintCode:旋转字符串

LintCode:旋转字符串

Python

class Solution:
    # @param s: a list of char
    # @param offset: an integer 
    # @return: nothing
    def rotateString(self, s, offset):
        # write you code here
        if len(s) == 0 :
            return s
        m = len(s)
        offset %= m 
        n = m - offset
        tmp = s[n:]
        while n > 0:
            s[n + offset-1] = s[n-1]
            n -= 1
        for i in range(offset):
            s[i] = tmp[i]

Java

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.length == 0){
            return;
        }
        int m = str.length;
        offset %= m;
        int n = m - offset;
        char[] tmp = new char[offset];
        int k = 0;
        for(int i=n; i<m; i++){
            tmp[k++] = str[i];
        }
        while(n>0){
            str[n+offset-1] = str[n-1];
            n --;
        }
        for(int i=0; i<offset; i++){
            str[i] = tmp[i];
        }
    }
}

你可能感兴趣的:(LintCode:旋转字符串)