Check If One String Is Rotation of Another | Java 8 Tricky Interview Coding Question

 Hi All,

Today I have released new video on "Check If One String Is Rotation of Another | Java 8 Tricky Interview Coding Question"


This is frequently asked question in Java Interview.


Please watch full video, share, like and Subscribe Youtube channel and press bell icon. So you will get latest video notification.

 


 package org.practice.basicprgms;


import java.util.stream.IntStream;


public class CheckStringIsRotationOfAnother {


public static void main(String[] args) {

String s1 = "ABCD";

String s2 = "BCDA";

boolean result = false;

// Solution 1 : Using contains method

result = s1.length() == s2.length() &&

(s1 + s1).contains(s2);

System.out.println("Using contains method : Is Rotation String : "+ result);

// Solution 2 : Using Regular Expression

result = false;

result = s1.length() == s2.length() &&

(s1 + s1).matches(".*"+ s2 + ".*");

System.out.println("Using Regular Expression : Is Rotation String : "+ result);


// Solution 3 : Using indexOf method

result = false;

result = s1.length() == s2.length() &&

(s1 + s1).indexOf(s2) != -1;

System.out.println("Using indexOf method : Is Rotation String : "+ result);


// Solution 4 : Using rangeClosed and anyMatch method

result = false;

result = s1.length() == s2.length() &&

IntStream.rangeClosed(0, s1.length())

.anyMatch(i -> (s1.substring(i) + s1.substring(0, i)).equals(s2));

System.out.println("Using rangeClosed and anyMatch method : Is Rotation String : "+ result);

// Solution 5 : Using rangeClosed, filter and findFirst method

result = false;

result = s1.length() == s2.length() &&

IntStream.rangeClosed(0, s1.length())

.mapToObj(i -> s1.substring(i) + s1.subSequence(0, i))

.filter(str -> str.equals(s2))

.findFirst()

.isPresent();

System.out.println("Using rangeClosed, filter and findFirst method : Is Rotation String : "+ result);

// Solution 6: Using rangeClosed, mapToObj and anyMatch method

result = false;

result = s1.length() == s2.length() &&

IntStream.rangeClosed(0, s1.length())

.mapToObj(i -> s1.substring(i) + s1.subSequence(0, i))

.anyMatch(str -> str.equals(s2));

System.out.println("Using rangeClosed, mapToObj and anyMatch method : Is Rotation String : "+ result);

}

}


output:

Using contains method : Is Rotation String : true

Using Regular Expression : Is Rotation String : true

Using indexOf method : Is Rotation String : true

Using rangeClosed and anyMatch method : Is Rotation String : true

Using rangeClosed, filter and findFirst method : Is Rotation String : true

Using rangeClosed, mapToObj and anyMatch method : Is Rotation String : true

Post a Comment

0 Comments