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

题目

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

思路

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

代码一

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位。this

代码二

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;
    }
};

修改完以后代码就算是完美了,各类状况都考虑到了。code

注意

若是想到了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 substringget

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

Exceptions
std::out_of_range if pos > size()it

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()).

总结

  • 要考虑的各类陷阱和异常状况,实际笔试和面试中不会有这么屡次机会给咱们试错!

个人简书连接

相关文章
相关标签/搜索