String rotation (simple)
September 26, 2020
Question source: Likou
Problem solving
- Violence
simulates rotation, and returns true if it is right, the speed is too slow
class Solution {
public boolean isFlipedString(String s1, String s2) {
if(s1.length()!=s2.length()) return false;
if(s1.length()==0 && s2.length()==0) return true;
for(int i=0;i<s1.length();i++){
if(s1.charAt(i)==s2.charAt(0)){
if((s1.substring(i,s1.length())+s1.substring(0,i)).equals(s2)) return true;
}
}
return false;
}
}
- Splicing
Use s2 for self-stitching. If s2 is rotated by s1, there must be an s1 in s2+s2
class Solution {
public boolean isFlipedString(String s1, String s2) {
if(s1.length()!=s2.length()) return false;
return (s2+s2).indexOf(s1)!=-1;
}
}