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

  • 相关阅读:
    shell(计算机壳层)(二)
    Linux Bash Shell快速入门 (三)
    Lua
    bash
    Perl
    脚本语言
    JSP中获取客户端或浏览端信息的方式
    linux环境变量
    逆向思维
    【maven】IDEA:存在jar包,pom.xml文件没报错,但是Maven-Project-Dependencies有红线报错
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/14961372.html
Copyright © 2011-2022 走看看