Online Judge Solutions

Sunday, December 7, 2014

LintCode: Rotate String

Given a string and an offset, rotate string by offset. (rotate from left to right)
Example
Given "abcdefg" and offset=3, return "efgabcd"
Note: The offset means count from the end

 
class Solution {
private:
    void rotateHelper(string &A, int k, int n)
    {
        int i = 0;
        while(i + k < n) 
        {
            for(; i+k < n; i++) {
                char t = A[i];
                A[i] = A[i+k];
                A[i+k] = t;
            }   
            
            k = k - n % k; 
        }
    }

public:
    /**
     * param A: A string
     * param offset: Rotate string with offset.
     * return: Rotated string.
     */
     string rotateString(string A, int offset) {
        if (A.length()< 2) return A;
        int K = A.length() - offset % A.length();
        
        rotateHelper(A, K, A.length());
        return A;
    }
};

=============================================================
class Solution2 {

private:
    void reverse(string &A, int start, int end)
    {
        while(start < end)
        {
            char t = A[start];
            A[start++] = A[end];
            A[end--] = t;
        }
    }

public:
  /**
     * param A: A string
     * param offset: Rotate string with offset.
     * return: Rotated string.
     */
   
    string rotateString(string A, int offset) {
        if (A.length()< 2) return A;
       
        int N = offset % A.length();
        reverse(A, 0, A.length()-N-1);
        reverse(A, A.length()-N, A.length()-1);
        reverse(A, 0, A.length()-1);
        return A;
    }
};

No comments:

Post a Comment