【6】Decide if one string is a rotation of another string or not

阳文轩
2023-12-01

Question: Assume you have a method isSubstring which checks if one word is a substring ofanother. Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 usingonly one call to isSubstring (i.e., “waterbottle” is a rotation of “erbottlewat”). 

package CareerCup;

public class RotationString 
{
	public RotationString(){}
	
	public boolean isSubString(String str1,String str2)
	{
		if(str1.indexOf(str2)==-1) return false;
		return true;
	}
	
	public boolean IsRotation(String str1,String str2)
	{
		if(str1.length()==str2.length() && str1.length() > 0)
		{	
			String str1str1 = str1+str1;
			return isSubString(str1str1,str2);
		}
		return false;
	}
	
	public static void main(String[] args)
	{
		String str1 = "erbottlewat";
		String str2 = "waterbottle";
		RotationString rs = new RotationString();
		if(rs.IsRotation(str1, str2))
			System.out.println(str2+" is a rotation of "+str1+"!");
		else 
			System.out.println(str2+" is not a rotation of "+str1+"!");
	}
}


 类似资料: