zoukankan      html  css  js  c++  java
  • lintcode :旋转字符串

    题目:

    给定一个字符串和一个偏移量,根据偏移量旋转字符串(从左向右旋转)

    样例

    对于字符串 "abcdefg".

    offset=0 => "abcdefg"
    offset=1 => "gabcdef"
    offset=2 => "fgabcde"
    offset=3 => "efgabcd"
    
    挑战

    在数组上原地旋转,使用O(1)的额外空间

    解题:

    这个题目和这一题很像,前部分逆序,后部分逆序,整体逆序,这里注意的是offeset会大于字符串长度的情况,所以要对offeset处理:offeset = offeset%len

    Java程序:

    public class Solution {
        /**
         * @param str: an array of char
         * @param offset: an integer
         * @return: nothing
         */
        public void rotateString(char[] str, int offset) {
            // write your code here
            int left = 0;
            int right = str.length-1;
            
            if(str!=null && str.length!=0){
                offset = offset%(right+1);
                rotateStr(str,0,right - offset);
                rotateStr(str,right - offset+1,right);
                rotateStr(str,0,right);
                
            }
        }
        public void rotateStr(char[]str,int left,int right){
            char tmp;
            while(left<right){
                tmp = str[left];
                str[left] = str[right];
                str[right] = tmp;
                left++;
                right--;
            }
        }
    }
    View Code

    总耗时: 831 ms

    Python程序:

    class Solution:
        # @param s: a list of char
        # @param offset: an integer 
        # @return: nothing
        def rotateString(self, s, offset):
            # write you code here
            if s!=None and len(s)!=0:
                left = 0
                right = len(s) - 1
                offset = offset%(right+1)
                self.rotateStr(s,0,right - offset)
                self.rotateStr(s,right - offset + 1,right)
                self.rotateStr(s,0,right)
            
            
        def rotateStr(self,s,left,right):
            while left<right:
                tmp = s[left]
                s[left] = s[right]
                s[right] = tmp
                left += 1
                right -= 1
                
    View Code

    总耗时: 233 ms

  • 相关阅读:
    linux安装mysql8
    linux安装nginx
    linux tp5隐藏index.php
    E45: 'readonly' option is set (add ! to override)
    linux安装git方法
    php-5.6 添加php_zip.dll拓展
    双向链表
    每日一题 为了工作 2020 0315 第十三题
    每日一题 为了工作 2020 03014 第十二题
    每日一题 为了工作 2020 03013 第十一题
  • 原文地址:https://www.cnblogs.com/bbbblog/p/4886379.html
Copyright © 2011-2022 走看看