Java Program for Check if a string can be formed from another string by at most X circular clockwise shifts
Last Updated :
25 Jan, 2022
Given an integer X and two strings S1 and S2, the task is to check that string S1 can be converted to the string S2 by shifting characters circular clockwise atmost X times.
Input: S1 = “abcd”, S2 = “dddd”, X = 3Â
Output: YesÂ
Explanation:Â
Given string S1 can be converted to string S2 as-Â
Character “a” – Shift 3 times – “d”Â
Character “b” – Shift 2 times – “d”Â
Character “c” – Shift 1 times – “d”Â
Character “d” – Shift 0 times – “d”
Input: S1 = “you”, S2 = “ara”, X = 6Â
Output: YesÂ
Explanation:Â
Given string S1 can be converted to string S2 as –Â
Character “y” – Circular Shift 2 times – “a”Â
Character “o” – Shift 3 times – “r”Â
Character “u” – Circular Shift 6 times – “a” Â
Approach: The idea is to traverse the string and for each index and find the difference between the ASCII values of the character at the respective indices of the two strings. If the difference is less than 0, then for a circular shift, add 26 to get the actual difference. If for any index, the difference exceeds X, then S2 can’t be formed from S1, otherwise possible.Â
Below is the implementation of the above approach:Â
Java
import java.io.*;
import java.util.*;
class GFG{
static void isConversionPossible(String s1,
String s2,
int x)
{
int diff = 0 , n;
n = s1.length();
for ( int i = 0 ; i < n; i++)
{
if (s1.charAt(i) == s2.charAt(i))
continue ;
diff = (( int )(s2.charAt(i) -
s1.charAt(i)) + 26 ) % 26 ;
if (diff > x)
{
System.out.println( "NO" );
return ;
}
}
System.out.println( "YES" );
}
public static void main (String[] args)
{
String s1 = "you" ;
String s2 = "ara" ;
int x = 6 ;
isConversionPossible(s1, s2, x);
}
}
|
Time Complexity:O(N),N=Length(S1)
Auxiliary Space:O(1)
Please refer complete article on Check if a string can be formed from another string by at most X circular clockwise shifts for more details!
Share your thoughts in the comments
Please Login to comment...