Version: Next
面试题 01.09 字符串轮转
面试题 01.09. String Rotation LCCI
难度 简单
字符串轮转。给定两个字符串s1
和s2
,请编写代码检查s2
是否为s1
旋转而成(比如,waterbottle
是erbottlewat
旋转后的字符串)。
Given two strings, s1
and s2
, write code to check if s2
is a rotation of s1
(e.g.,"waterbottle" is a rotation of"erbottlewat"). Can you use only one call to the method that checks if one word is a substring of another?
Example 1:
Input: s1 = "waterbottle", s2 = "erbottlewat"
Output: True
Example 2:
Input: s1 = "aa", s2 = "aba"
Output: False
思路
- 判断
str1
与str2
长度是否相等- 把原字符串直接首尾拼接
str1 + str1
- 判断
str2
是否为str1
的子串
public class _01_09字符串轮转 {
public boolean isFlipedString(String s1, String s2) {
if (s1 == null || s2 == null) return false;
if (s1.length() != s2.length()) return false;
return (s1 + s1).contains(s2);
}
public static void main(String[] args) {
String s1 = "waterbottle", s2 = "erbottlewat";
boolean b = new _01_09字符串轮转().isFlipedString(s1, s2);
System.out.println("b = " + b);
}
}