首页 > 其他 > 详细

Lincode刷题No.8

时间:2019-11-02 13:49:43      阅读:98      评论:0      收藏:0      [点我收藏+]

8.Rotate String

lintcode

题解:

class Solution {
public:
    /**
     * @param str: An array of char
     * @param offset: An integer
     * @return: nothing
     */
    void rotateString(string &str, int offset) {
        string t_str;
        int len = str.length();
        if (len == 0 || offset == 0)return;
        int new_offset = offset % len;
    
        int j = len - 1;
        for (int i = 0; i< new_offset; i++)
        {
            t_str.insert(0,1 ,str[j]);
            j--;
        }
    
        if (new_offset == 0)new_offset = len;
        for (int i=0;i!=j+1;i++)
        {
            t_str.push_back(str[i]);
        }
    
        for (int i = 0; i < len; i++)
        {
            str[i] = t_str[i];
        }
    }
};

没能想出O(1)的题解

所以就直接暴力解了,复杂度勉强能接受

反思:

  • 一开始没看清题目就直接编程,以为offset表示的是字符串的从0开始的下标,其实不然,实际题目的要求是把 offset%len 个末尾字符移动到前面. 就这一点卡了很久,所以正确理解题目很关键,不要急于码代码.
  • 当 offset > len 时,可以通过 offset%len处理一下,避免重复的循环

Lincode刷题No.8

原文:https://www.cnblogs.com/virgildevil/p/11781414.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!