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

  • 相关阅读:
    常用的服务器简介
    PHP Proxy 负载均衡技术
    Hexo 博客Next 搭建与美化主题
    Tomcat PUT方法任意文件上传(CVE-2017-12615)
    哈希爆破神器Hashcat的用法
    内网转发随想
    Oauth2.0认证
    Github搜索语法
    记一次挖矿木马清除过程
    利用ICMP进行命令控制和隧道传输
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/14961372.html
Copyright © 2020-2023  润新知