反转子串
题目描述
给定2个字符串s1和s2,请判断s2是否为s1旋转而成,返回bool值。字符串中字符为英文字母和空格,区分大小写,字符串长度小于等于1000。
测试样例:
“Hello world”,"worldhello "
返回:false
“waterbottle”,“erbottlewat”
返回:true
思路
判断 s2 是否为 s1 的旋转, 可以考虑 String s = s1+s1, 然后 判断 s1 是否包含 s2。如果包含返回true, 如果遍历完都没有找到,返回false。
注意: s.substring(beginIndex, endIndex); [beginIndex, endIndex)
代码
package june.code.byhehe.book.GoldBook;
public class CM8ReverseSubStr {
public static void main(String[] args) {
String s1 = "waterbottle";
String s2 = "erbottlewat";
CM8 cm8 = new CM8();
System.out.println(cm8.checkReverseEqual(s1, s2));
}
}
class CM8{
// 方法 s = s1+s1 ,判断 s1是否包含s2
public boolean checkReverseEqual(String s1, String s2) {
// write code here
// 首先判断长度
if(s1.length()!=s2.length())
return false;
String s = s1+s1;
// 使用 子串 判断
int length = s2.length();
for (int i = 0; i < s.length() - length; i++) {
// System.out.println(s.substring(i,i+length)+" "+s2);
if(s.substring(i, i+length).equals(s2))
return true;
}
return false;
}
}
总结
未做到 bug free , 有些粗心, 错误处:s.substring(0, length) 。
这里补充一种 使用正则表达式的思路
其实 和 第一种基本一样, 只是对 for 循环进行了改造,事实上 还是一样的。
public boolean checkReverseEqual2(String s1, String s2) {
// write code here
// 首先判断长度
if(s1.length()!=s2.length())
return false;
s2 = "^.*"+s2+".*$";
String s = s1+s1;
// 使用 子串 判断
int length = s2.length();
if(s.matches(s2)){
// System.out.println("匹配");
return true;
}
return false;
}