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的一百种用法

  • 相关阅读:
    面向过程编程
    生成器
    迭代器
    装饰器
    函数对象与闭包
    名称空间和作用域
    Django中的as_view方法源码分析
    DRF3序列化反序列化
    DRF4级联与外键字段
    django--BBS项目,后端业务逻辑整理
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/14961372.html
Copyright © 2011-2022 走看看