Rotate String

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"
offset=4 => "defgabc"
offset=5 => "cdefgab"
offset=6 => "bcdefga"
offset=7 => "abcdefg"
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;
        
        int len = str.length;
        offset = offset % len;
        
        char[] temp = new char[offset];
        
        for (int i = 0; i < offset; i++) {
            temp[i] = str[str.length-1-i];
        }
        
        for (int i = 0; i<str.length - offset; i++) {
            str[str.length -1 - i] = str[str.length -1 - offset - i];
        }
        
        for (int i = 0; i < offset; i++) {
            str[i] = temp[offset- 1 -i];
        }
        
    }
}

public class Solution { 
    public void rotateString(char[] str, int offset) { 
        int len = str.length; 
        char[] newstr = new char[len+1]; 
        if (str == null || str.length == 0) return; 
        //modify offset if offset > length; 
        offset = offset % len; 
        for (int i = 0; i < offset; i++) { 
            newstr[i] = str[len-offset+i]; 
         } 
         for (int i = offset; i < len; i++) { 
            newstr[i] = str[i-offset]; 
        } 
        for (int i = 0; i < len; i++) { 
            str[i] = newstr[i]; 
        } 
        return; 
    }
}

三步翻转法?O(1) extra memory

public class Solution { 
      public void rotateString(char[] str, int offset) { 
            if (str == null || str.length == 0) { return; } 
            int len = str.length; 
            offset = offset % len; 
            reverse(str, 0, len-offset-1); 
            reverse(str, len-offset, len-1); 
            reverse(str, 0, len-1); return; } 
     public void reverse(char[] str, int start, int end) { 
            while (start <= end) { 
                  char temp = str[start]; 
                  str[start] = str[end]; 
                  str[end] = temp; 
                  start++; 
                  end--; 
            } 
      }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容