问题描述: 给定两个字符串, s 和 goal。如果在若干次旋转操作之后,s 能变成 goal ,那么返回 true 。s 的 旋转操作 就是将 s 最左边的字符移动到最右边。 若 s = ‘abcde’,在旋转一次之后结果就是’bcdea’ 。 样例输入: 代码如下:两种解法
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class RotateString {
public static boolean rotateString(String s, String goal) {
StringBuilder stringBuilder=new StringBuilder(s);
if (s.equals(goal)) return true;
for (int i = 0; i <s.length() ; i++) {
char temp=stringBuilder.charAt(0);
stringBuilder=new StringBuilder(stringBuilder.substring(1));
stringBuilder.append(temp);
if (stringBuilder.toString().equals(goal)) return true;
}
return false;
}
public static boolean rotateString1(String s, String goal) {
return s.length() == goal.length() && (s + s).contains(goal);
}
public static void main(String[] args) {
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(System.in));
String s= null;
String goal= null;
try {
s = bufferedReader.readLine();
goal = bufferedReader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(rotateString(s,goal));
System.out.println(rotateString1(s,goal));
}
}
运行结果如下: **
|