-
Notifications
You must be signed in to change notification settings - Fork 63
/
Copy pathStringRotationOfAnother.java
66 lines (53 loc) · 1.54 KB
/
StringRotationOfAnother.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package com.java.strings;
import java.util.Scanner;
/*
* Check Given String is Rotation of Another String
* -------------------------------------------------
*
* Say String 1 : abcd
* Say String 2 : bcda
* String 2 is rotation of string 1
*
* Rotation means order should be maintained,
* same set of characters forming another string
* without changing its order ( like b follows a, d follows c)
*
*/
public class StringRotationOfAnother {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the string 1 ::");
String str1 = scanner.nextLine().trim();
System.out.println("Enter the string 2 ::");
String str2 = scanner.nextLine().trim();
if(checkStringRotation(str1, str2))
System.out.println("String 2 is rotation of String 1");
else
System.out.println("String 2 is NOT rotation of String 1");
scanner.close();
}
private static boolean checkStringRotation(String str1,String str2){
if(str1 == null || str2 == null)
return false;
if(str1.length() != str2.length())
return false;
//add string 1 with string 1 itself
//it helps to identify its rotation
str1 = str1 + str1;
if(str1.contains(str2))
return true;
return false;
}
}
/*
OUTPUT
Enter the string 1 :: greeting
Enter the string 2 :: inggreet
String 2 is rotation of String 1
Enter the string 1 :: abcdef
Enter the string 2 :: bcdefa
String 2 is rotation of String 1
Enter the string 1 :: java
Enter the string 2 :: jaav
String 2 is NOT rotation of String 1
*/