《Cracking the Coding Interview》——第1章:数组和字符串——题目8
2024-09-04 03:24:35
2014-03-18 02:12
题目:判断一个字符串是否由另一个字符串循环移位而成。
解法:首先长度必须相等。然后将第一个串连拼两次,判断第二个串是否在这个连接串中。
代码:
// 1.8 Assume you have a method isSubstring which checks if one word is a substring of another. Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 using only one call to isSubstring (i.e., “waterbottle” is a rotation of “erbottlewat”).
#include <cstdio>
#include <cstring>
using namespace std; class Solution {
public:
bool isStringRotation(char *s1, char *s2) {
if (s1 == nullptr || s2 == nullptr) {
return false;
} int len1, len2; len1 = strlen(s1);
len2 = strlen(s2);
if (len1 != len2) {
return false;
} const int MAXLEN = ;
static char tmp[MAXLEN]; tmp[] = ;
strcat(tmp, s1);
strcat(tmp, s1);
return strstr(tmp, s2) != nullptr;
}
private:
bool isSubstring(char *haystack, char *needle) {
if (haystack == nullptr || needle == nullptr) {
return false;
} return strstr(haystack, needle) != nullptr;
}
}; int main()
{
char s1[];
char s2[];
Solution sol; while (scanf("%s%s", s1, s2) == ) {
printf("\"%s\" is ", s2);
if (!sol.isStringRotation(s1, s2)) {
printf("not ");
}
printf("a rotation of \"%s\".\n", s1);
} return ;
}
最新文章
- windows XP 神key
- ajax post(copy part)
- 【redmine】密码忘了后重新设置
- Java文件编码格式转换
- zoj 3537 Cake 区间DP (好题)
- Spfa费用流模板
- Tree( 树) 组件[1]
- 关于Ajax的type为post提交方式出现请求失效问题
- 用cas来实现php的单点登陆
- Struts2学习笔记NO.1------结合Hibernate完成查询商品类别简单案例(工具IDEA)
- 实际项目开发需要注意的tips
- cmdb部署
- Vue-devtools 安装浏览器调试
- table设置上下左右边距不一样-html
- Ubuntu 16.04 LTS 下安装 ibus-rime 输入法
- CSS3:文字属性
- Shell学习笔记之shell脚本和python脚本实现批量ping IP测试
- nodejs tutorials
- 【UVALive】2965 Jurassic Remains(中途相遇法)
- C语言文法推导
热门文章
- POJ-3614 Sunscreen---贪心+优先队列
- Codeforces Codeforces Round #383 (Div. 2) E (DFS染色)
- ssh key一键自动化生成公钥私钥,并自动分发上百服务器免密码交互
- 最终类object 和内部类
- P1217 [USACO1.5]回文质数 Prime Palindromes
- LIS的string用法
- Ajax (Asynchronous javascript xml) 搜索框核心代码(JQuery) Ajax判断用户名存在核心代码 附:原生js的Ajax代码 其中有json的一句话解释
- iOS 实时监测网络状态(通过Reachability)
- 浅谈MySQL字符集
- Shell 入门笔记(一)