[刷题]剑指offer之左旋转字符串

题目

题目:汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串模拟这个指令的运算结果。对于一个给定的字符序列S,请你把其循环左移n位后的序列输出。例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。是不是很简单?OK,搞定它!

思路

这个题乍一看超级简单,将左边的长度为n的子字符串拿出来,拼接在字符串的后面即可。

代码一

class Solution {
public:
    string LeftRotateString(string str, int n) {
        string str1 = str.substr(0,n);
        string str2 = str.substr(n);
        return str2+str1;
    }
};

然后提交之后通过不了。。。terminate called after throwing an instance of 'std::out_of_range' what(): basic_string::substr: __pos (which is 6) > this->size() (which is 0)。意思就是str的大小是0,却索引了字符串的第6位。

代码二

class Solution {
public:
    string LeftRotateString(string str, int n) {
        if(str.length() == 0)
            return str;
        string str1 = str.substr(0,n);
        string str2 = str.substr(n);
        return str2+str1;
    }
};

修改代码后,就通过了。但是仔细想一想,n有可能比字符串的长度大,这个时候还是可能发生越界,但是这题的案例应该没设计好,没有暴露问题!如果n大于str.length(),左移n位其实就相当于左移n % str.length()位。

代码三

class Solution {
public:
    string LeftRotateString(string str, int n) {
        if(str.length() == 0)
            return str;
        n %= str.size();
        string str1 = str.substr(0,n);
        string str2 = str.substr(n);
        return str2+str1;
    }
};

修改完之后代码就算是完美了,各种情况都考虑到了。

注意

如果想到了n可能大于字符串的长度,却没有想到字符串可能为空,那么n %= str.length()就会报浮点错误:您的程序运行时发生浮点错误,比如遇到了除以 0 的情况的错误。

C++求子串

std::string::substr

Returns a substring [pos, pos+count). If the requested substring extends past the end of the string, or if count == npos, the returned substring is [pos, size()).

Parameters
pos - position of the first character to include
count - length of the substring

Return value
String containing the substring [pos, pos+count).

Exceptions
std::out_of_range if pos > size()

Complexity
Linear in count

Important points

  1. The index of the first character is 0 (not 1).
  2. If pos is equal to the string length, the function returns an empty string.
  3. If pos is greater than the string length, it throws out_of_range. If this happen, there are no changes in the string.
  4. If for the requested sub-string len is greater than size of string, then returned sub-string is [pos, size()).

总结

  • 要考虑的各种陷阱和异常情况,实际笔试和面试中不会有这么多次机会给我们试错!

我的segmentfault链接

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 前言 最先接触编程的知识是在大学里面,大学里面学了一些基础的知识,c语言,java语言,单片机的汇编语言等;大学毕...
    oceanfive阅读 8,501评论 0 7
  • 第2章 基本语法 2.1 概述 基本句法和变量 语句 JavaScript程序的执行单位为行(line),也就是一...
    悟名先生阅读 9,754评论 0 13
  • 7月份,基本已经到了动手阶段了。孩子们还在忙暑假活动,准备最后的标化冲刺,总之,各种事件,时间不够用, 亲妈就考虑...
    旺妈聊留学阅读 6,200评论 4 20
  • 【论语心得092】安贫是因为乐道 【原文】子曰:“贤哉,回也!一箪食,一瓢饮,在陋巷,人不堪其忧,回也不改其乐。贤...
    国学应用讲习所阅读 3,582评论 0 0
  • 黄昏后,灯火如昼 匆匆行色,影扑朔 丝丝雨,落翩翩 风吹叶舞,残绿惜惜别 更翠滴,木兰花下梦痕新 蔷薇语,醉冰清 ...
    烟雨心清阅读 1,891评论 1 7

友情链接更多精彩内容