zoukankan      html  css  js  c++  java
  • 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"

    Solution:

     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         if (A.length==0) return A;
     9         offset = offset % A.length;
    10         if (offset == 0) return A;
    11         int len = A.length;
    12         //Store the rotated char in buffer.
    13         char[] buff = new char[offset];
    14         for (int i=len-offset;i<len;i++)
    15             buff[i-len+offset] = A[i];
    16 
    17         //Move the left chars to right.
    18         for (int i=len-offset-1;i>=0;i--)
    19             A[i+offset] = A[i];
    20 
    21         //Put the chars in buff into array.
    22         for (int i=0;i<offset;i++)
    23             A[i] = buff[i];
    24 
    25         return A;
    26     }
    27 };
  • 相关阅读:
    编写登陆认证程序
    模拟实现一个ATM + 购物商城程序
    三级菜单
    12 场景制造
    11 Unity Editor界面
    3.7练习题
    Coolite 弹窗妙用
    Nginx反向代理 实现Web负载均衡
    MySQL 架构
    Lnmmp
  • 原文地址:https://www.cnblogs.com/lishiblog/p/4183941.html
Copyright © 2011-2022 走看看