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

news/2024/7/5 4:54:54

题目

题目:汇编语言中有一种移位指令叫做循环左移(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()).

总结

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

我的简书链接


http://www.niftyadmin.cn/n/4110240.html

相关文章

从高频笔/面试题思考Android学习/进阶路线(Java篇)

写在前面 标题谈进阶,属实有一些夸大。 我一直在思考什么样的文章才是一篇好文章,我的定义是首先要有人看,其次重要的是内部有价值。所以针对于这个出发点,我决定从大家比较关注的面试题入手,然后尝试从中分析对Androi…

工具之xray使用教程

xray扫描器 xray是一种功能强大的扫描工具。xray 社区版是长亭科技推出的免费白帽子工具平台,目前社区有 xray 漏洞扫描器和 Radium 爬虫工具,由多名经验丰富的安全开发者和数万名社区贡献者共同打造而成。 下载地址 https://github.com/chaitin/xray…

scala 学习笔记六 推导

1、介绍 在Scala中,推导将生成器、过滤器、和定义组合在一起。 2、例子 有一种将result用作val(而不是var)的方式,:“就地”构建result,而不是逐项构建,利用yield关键字,当你声明yield n时,它会把n交出来&a…

过度紧张,驱之有道

过度紧张,驱之有道 精神紧张一般分为弱的.适度的和过度的三种。人们需要适度的精神紧张;因为这是人们解决问题的必要条件;但是过度的精神紧张却不利于问题的解决。那么,应怎样做才能解决人的过度精神紧张而达到心理平衡呢&#xf…

Java知多少(笔记)

1、&与&& eg: String s;if(s !null && s.equals("")){} //类似于物理电路一样,当条件一符合时才执行条件二if(s !null & s.equals("")){}//条件一二执行 此时会报空指针错误 复制代码2.一个.java文件中能否包含多个类…

内网之权限维持

一,shift后门 方法1:修改注册表-映像劫持 REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\sethc.exe" /v Debugger /t REG_SZ /d "C:\windows\system32\cmd.exe" 命令说明&#xff1a…

safari_通过Safari Technology Preview尽早试用Safari的新功能

safariSome of the coolest new features in the upcoming macOS 10.13 High Sierra are in Safari, and you can try them out now without upgrading your entire operating system. 即将推出的macOS 10.13 High Sierra中的一些最酷的新功能都在Safari中,您可以立…

内网之横向移动之IPC

一,IPC IPC(Internet Process Connection)共享命名管道的资源,是为了实现进程间通信而开放的命名管道。IPC可以通过验证用户名和密码获得相应的权限。 二,ipc$与空连接,139,445端口,默认共享的关系 1,ipc$与空连接: 不需要用户…