Java来确定一个字符串是否是另一字符串的旋转
Java程序来确定一个字符串是否是另一字符串的旋转
在此程序中,我们需要检查一个字符串是否是另一字符串的旋转。
String 1: abcde
String 2: deabc
String 1 + String 1: abcdeabcde
考虑上面的示例,假设我们需要检查字符串2是否为字符串1的旋转。要找到此字符串,我们将字符串1与字符串1连接起来。然后,尝试在串联的字符串中找到字符串2 。如果字符串2存在于串联字符串中,则字符串2是字符串1的旋转。字符串2 deabc在串联字符串的索引3中找到。因此,deabc是abcde的旋转。
算法
步骤1: START
步骤2: DEFINE字符串str1 ="abcde",str2 ="deabc"
步骤3: 如果str1的长度不等于str2,则打印"否"
否则转到步骤4
步骤4: 用str1合并str1。
步骤5: 如果str1中存在str2,则打印"是",否则打印"否"。
步骤6: END
程序:
public class StringRotation
{
public static void main(String[] args) {
String str1 = "abcde", str2 = "deabc";
if(str1.length() != str2.length()){
System.out.println("Second string is not a rotation of first string");
}
else {
//Concatenate str1 with str1 and store it in str1
str1 = str1.concat(str1);
//Check whether str2 is present in str1
if(str1.indexOf(str2) != -1)
System.out.println("Second string is a rotation of first string");
else
System.out.println("Second string is not a rotation of first string");
}
}
}
输出:
Second string is a rotation of first string