力扣796题---旋转字符串
给定两个字符串,s和goal。如果在若干次旋转操作之后,s能变成goal,那么返回true。
s的旋转操作 就是将s最左边的字符移动到最右边。
例如, 若s = 'abcde',在旋转一次之后结果就是'bcdea'。
示例1:
输入: s = "abcde", goal = "cdeab"
输出: true
示例2:
输入: s = "abcde", goal = "abced"
输出: false
提示:
1 <= s.length, goal.length <= 100
s和goal由小写英文字母组成
方法一:搜索子字符串
如果s与goal的长度不一样,那么无论怎么旋转,s 都不能得到goal,返false。
字符串s+s 包含了所有s可以通过旋转操作得到的字符串,只需要检查goal是否为s+s的子字符串即可。
方法代码:
public boolean rotateString(String s, String goal) {
return s.length() == goal.length() && (s + s).contains(goal);
}
测试:
public class Main {
public static void main(String[] args) {
String str = "abcdefg";
String goal = "cdefcab";
Main solution = new Main();
System.out.println(solution.rotateString(str, goal));
}
public boolean rotateString(String s, String goal) {
return s.length() == goal.length() && (s + s).contains(goal);
}
}
输出:true
方法二:模拟
首先,如果s和goal的长度不一样,那么无论怎么旋转,s都不能得到goal,返回false。
在长度一样(都为n)的前提下,假设s旋转i位,则与goal中的某一位字符goal[j]对应的原s中的字符应该为s[(i+j)mod n]。在固定i的情况下,遍历所有 j,若对应字符都相同,则返回true。否则,继续遍历其他候选的i。若所有的i都不能使s变成goal,则返回false。
方法代码:
public boolean rotateString(String s, String goal) {
int m = s.length(), n = goal.length();
if (m != n) {
return false;
}
for (int i = 0; i < n; i++) {
boolean flag = true;
for (int j = 0; j < n; j++) {
if (s.charAt((i + j) % n) != goal.charAt(j)) {
flag = false;
break;
}
}
if (flag) {
return true;
}
}
return false;
}
测试:
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
//BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = "abcdefg";
String goal = "cdefgab";
Main solution = new Main();
System.out.println(solution.rotateString(str, goal));
}
public boolean rotateString(String s, String goal) {
int m = s.length(), n = goal.length();
if (m != n) {
return false;
}
for (int i = 0; i < n; i++) {
boolean flag = true;
for (int j = 0; j < n; j++) {
if (s.charAt((i + j) % n) != goal.charAt(j)) {
flag = false;
break;
}
}
if (flag) {
return true;
}
}
return false;
}
}
输出:true