-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidShuffle.cpp
More file actions
51 lines (48 loc) · 1.48 KB
/
validShuffle.cpp
File metadata and controls
51 lines (48 loc) · 1.48 KB
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
//Q-Java Program to Check if a string is a valid shuffle of two distinct strings
//1XY2 is a valid shuffle of XY and 12
//Y12X is not a valid shuffle of XY and 12
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
public static boolean isShuffle(String first,String second,String result)
{
// check length of result is same as
// sum of result of first and second
if(first.length()+second.length()!=result.length())
return false;
// variables to track each character of 3 strings
int i=0,j=0,k=0;
// iterating through all characters of result
while(k<result.length())
{
// check if first character of result matches with first character of first string
if(i<first.length() && first.charAt(i)==result.charAt(k))
i++;
// check if first character of result matches with first character of second string
else if(j<second.length() && second.charAt(j)==result.charAt(k))
j++;
// if the character doesn't match
else
return false;
//next char of result
k++;
}
if(i<first.length() || j<second.length())
return false;
return true;
}
public static void main (String[] args) throws java.lang.Exception
{
String first="AB";
String second="12";
String[] results={"A12B","A21B"};
for(String result :results){
if(isShuffle(first,second,result))
System.out.println(result+" is a valid shulffle of "+first+" & "+second);
else
System.out.println(result+" is a not valid shulffle of "+first+"&"+second);
}
}
}