zoukankan      html  css  js  c++  java
  • Java-旋转字符串

    描述

    旋转字符串

    给定一个字符串(以字符数组的形式给出)和一个偏移量,根据偏移量原地旋转字符串(从左向右旋转)。
    挑战
    在数组上原地旋转,使用O(1)的额外空间

    说明
    原地旋转意味着你要在s本身进行修改。你不需要返回任何东西。

    注意事项
    offset >= 0
    the length of str >= 0
    Make changes on the original input data

    样例

    样例 1:

    输入: str="abcdefg", offset = 3
    输出: str = "efgabcd"
    样例解释: 注意是原地旋转,即str旋转后为"efgabcd"
    样例 2:

    输入: str="abcdefg", offset = 0
    输出: str = "abcdefg"
    样例解释: 注意是原地旋转,即str旋转后为"abcdefg"
    样例 3:

    输入: str="abcdefg", offset = 1
    输出: str = "gabcdef"
    样例解释: 注意是原地旋转,即str旋转后为"gabcdef"
    样例 4:

    输入: str="abcdefg", offset =2
    输出: str = "fgabcde"
    样例解释: 注意是原地旋转,即str旋转后为"fgabcde"
    样例 5:

    输入: str="abcdefg", offset = 10
    输出: str = "efgabcd"
    样例解释: 注意是原地旋转,即str旋转后为"efgabcd"

    代码

    public class Solution {
        /**
         * @param str: An array of char
         * @param offset: An integer
         * @return: nothing
         */
        public void rotateString(char[] str, int offset) {
            if (str.length == 0){
                return;
            } 
            String t = "";
            for(int n = 0;n<str.length;n++){
                t+=str[n];
            }
            
            offset = offset%t.length();
            
            for(int i = 1;i<=offset;i++){
                t = t.charAt(t.length()-1)+t;
                t = t.substring(0,t.length()-1);
            }
            
            for(int n = 0;n<str.length;n++){
                str[n] = t.charAt(n);
            }
            
        }
    
    }
    
  • 相关阅读:
    [LeetCode] 85. 最大矩形
    [LeetCode] 84. 柱状图中最大的矩形
    [LeetCode] 83. 删除排序链表中的重复元素
    [LeetCode] 81. 搜索旋转排序数组 II
    [LeetCode] 82. 删除排序链表中的重复元素 II
    [LeetCode] 80. 删除排序数组中的重复项 II
    [LeetCode] 79. 单词搜索
    [LeetCode] 77. 组合
    转:快乐Node码农的十个习惯
    转:zookeeper3.4.5安装笔记
  • 原文地址:https://www.cnblogs.com/charlottepl/p/12750022.html
Copyright © 2011-2022 走看看