题目:汇编语言中有一种移位指令叫作循环左移(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 的状况
的错误。索引
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