Cracking the coding interview--Q1.8
来源:互联网 发布:sql指定的账户已存在 编辑:程序博客网 时间:2024/05/20 15:10
题目
原文:
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”).
译文:
假设你有一个isSubstring的方法,它可以检测一个字符串是否是另一个的子串,给出两个字符串s1和s2,仅调用一次isSubstring来检测s2是否是s1的旋转字符串,并写出代码(如:"waterbottle"是erbottlewat的旋转字符串)
解答
首先需要理解旋转字符串,只是部分字符左右旋转,原来的字母顺序可以说是不变的。而且题目要求只能使用一次isSubstring方法,显然在原字符串判断是不可能的。可以通过加长原字符串来判断,如:s1="apple", s2="pleap",将s1加长,两个s1相加,s1+s1="appleapple",则s2明显是s1+s1的子串,由此可得:
class Q1_8{public static boolean isRotation(String str1,String str2){if(str1.length()!=str2.length()||str1.length()<=0) return false;return isSubString(str1+str1,str2);}public static boolean isSubString(String str1,String str2){return str1.contains(str2);}public static void main(String[] args){String s1="apple";String s2="pleap";System.out.println(isRotation(s1,s2));}}
此题若有更好的方法,还望指教!
---EOF---
0 0
- Cracking the coding interview--Q1.8
- Cracking the coding interview--Q1.8
- Cracking the coding interview--Q1.8
- Cracking the coding interview--Q1.8
- Cracking the coding interview--Q1
- 【Cracking the coding interview】Q1.8(旋转字符串)
- Cracking The Coding Interview--Q1.1
- Cracking the coding interview Q1.1
- Cracking the coding interview--Q1.1
- Cracking the coding interview Q1.1
- Cracking the coding interview Q1.2
- Cracking the coding interview Q1.1
- Cracking the Coding Interview Chap1 Q1.1
- Cracking the Coding Interview Chap1 Q1.2
- Cracking the Coding Interview Chap1 Q1.3
- Cracking the Coding Interview Chap1 Q1.4
- Cracking the Coding Interview Chap1 Q1.5
- Cracking the coding interview--Q1.1
- [C++] 批量删除文件名多余的一个相同字符串
- 繫辭 下
- cocos2d-x ——HelloWorld
- jqeury 遍历函数的使用
- Taking Photos with the Camera(拍照)
- Cracking the coding interview--Q1.8
- Xcode中系统库文件libz.dylib的作用
- Linux C一站式学习习题答案5.3.1最大公约数
- 求两线段的交点(C++)
- Hadoop在淘宝中的应用
- <MEMORY>Project Euler NO32
- 繫辭 上
- Linux C一站式学习习题答案5.3.2Fibonacci数列
- [C/C++标准库]_[初级]_[标准库里提供的排序算法]