翻转子串
来源:互联网 发布:手机摄像头监控软件 编辑:程序博客网 时间:2024/06/05 04:59
题目描述
假定我们都知道非常高效的算法来检查一个单词是否为其他字符串的子串。请将这个算法编写成一个函数,给定两个字符串s1和s2,请编写代码检查s2是否为s1旋转而成,要求只能调用一次检查子串的函数。
给定两个字符串s1,s2,请返回bool值代表s2是否由s1旋转而成。字符串中字符为英文字母和空格,区分大小写,字符串长度小于等于1000。
测试样例:
“Hello world”,”worldhello ”
返回:false
“waterbottle”,”erbottlewat”
返回:true
思路一:
遍历整个字符串s1,截断字符串,将字符串拼接起来逐个和s2比较。
public boolean checkReverseEqual(String s1, String s2) { if (s1.length() != s2.length()) return false; char[] init = s1.toCharArray(); for (int i = 0; i < init.length; i++) { String preStr = String.valueOf(init, 0, i + 1); String lastStr = String.valueOf(init, i + 1, init.length - i - 1); String reverse = lastStr + preStr; if (reverse.equals(s2)) return true; } return false;}
思路二:
以s1=ABCD为例,我们先分析s1进行循环移位之后的结果:
ABCD->BCDA->CDAB->DABC->ABCD …….
假设我们把前面移走的数据进行保留:
ABCD->ABCDA->ABCDAB->ABCDABC->ABCDABCD…..
因此看出,对s1做循环移位,所得字符串都将是字符串s1s1的子字符串。如果s2可以由s1循环移位得到,则一定可以在s1s1上。
public boolean checkReverseEqual(String s1, String s2) { if (s1.length() != s2.length()) return false; String tmp = s1 + s1; return tmp.contains(s2);}
1 0
- 翻转子串
- 翻转子串
- 翻转子串(Java)
- 翻转子串
- 翻转子串
- 牛客网 | 翻转子串
- 翻转子串
- 翻转子串
- 字符串子串翻转
- 翻转子串
- 翻转子串
- 翻转子串
- nowcoder->翻转子串
- 翻转子串
- 翻转子串
- 翻转子串
- 第四天 翻转子串
- 翻转字符串中的子串
- 【myeclipse】显示插入的图形文件存储位置
- 基于AngularJS+NodeJS+Bootstrap+SpringMVC构建项目(1)
- 10G RAC VIP漂移后客户端的连接
- 41个Web开发者必须收藏的JavaScript实用技巧
- QTableView
- 翻转子串
- 在npm发布module
- 新闻管理系统(一)管理员登陆实现
- Linux注册tomcat为服务
- IOS 图片拉伸技巧
- 生产者,消费者的几个例子
- linux常用命令整理
- Camera sensor bring up
- css中的clip:rect() 只能在绝对定位的元素上使用