zoukankan      html  css  js  c++  java
  • 8 · Rotate String

    Description

    Given a string of char array and an offset, rotate the string by offset in place. (from left to right).
    In different languages, str will be given in different ways. For example, the string "abc" will be given in following ways:

    • Java: char[] str = {'a', 'b', 'c'};
    • Python:str = ['a', 'b', 'c']
    • C++:string str = "abc";

    offset >= 0
    the length of str >= 0
    In place means you should change strings in the function. You don't return anything.

    Example

    Example 1:

    Input:

    str = ""abcdefg"
    offset = 3

    Output:

    "efgabcd"

    Explanation:

    Note that it is rotated in place, that is, after str is rotated, it becomes "efgabcd".

    Example 2:

    Input:

    str = ""abcdefg"
    offset = 0

    Output:

    "abcdefg"

    Explanation:

    Note that it is rotated in place, that is, after str is rotated, it becomes "abcdefg".

    Example 3:

    Input:

    str = ""abcdefg"
    offset = 1

    Output:

    "gabcdef"

    Explanation:

    Note that it is rotated in place, that is, after str is rotated, it becomes "gabcdef".

    Example 4:

    Input:

    str = ""abcdefg"
    offset = 2

    Output:

    "fgabcde"

    Explanation:

    Note that it is rotated in place, that is, after str is rotated, it becomes "fgabcde".

    Example 5:

    Input:

    str = ""abcdefg"
    offset = 10

    Output:

    "efgabcd"

    Explanation:

    Note that it is rotated in place, that is, after str is rotated, it becomes "efgabcd".

        public void rotateString(char[] chars, int offset){
            if(chars.length == 0) return null
            offset = offset % chars.length;
    
            reverse(chars, 0, chars.length-1);
            reverse(chars, 0, offset-1);
            reverse(chars, offset, chars.length-1);
            return ;
        }
        private void reverse(char[] arr, int start, int end) {
            while(start < end) {
                char temp = arr[start];
                arr[start++] = arr[end];
                arr[end--] = temp;
            }       
        }

    reverse的一百种用法

  • 相关阅读:
    一个小厂算法工程师的2021个人年终总结
    优达学城 UdaCity 纳米学位
    Eclipse 常用可视化开发插件
    Android创建文件夹和文件
    Windows Mobile 播放声音文件
    C++实现顺序栈类
    c++实现的图类
    常见的字符串操作
    常见的链表操作
    取余数法实现哈希表(包括开放定址法和链地址法解决冲突)
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/14961372.html
Copyright © 2011-2022 走看看