Uploaded by Shreya Chinchmalatpure

Common Permutations

advertisement
Common Permutations
Shreya Chinchmalatpure
348
2046491245048
22-04-2023
Problem Description
Given two strings of lowercase letters, a and b, print the longest string x of lowercase letters
such that there is a permutation of x that is a subsequence of a and there is a permutation of x
that is a subsequence of b.
Input
Input file contains several lines of input. Consecutive two lines make a set of input. That
means in the input file line 1 and 2 is a set of input, line 3 and 4 is a set of input and so on.
The first line of a pair contains a and the second contains b. Each string is on a separate line
and consists of at most 1000 lowercase letters.
Output
For each set of input, output a line containing x. If several x satisfy the criteria above, choose
the first one in alphabetical order.
Input Example:
pretty
women
walking
down
the
street
Sample Output :
e
nw
et
Proposed Solution
1.Initialize a BufferedReader object to read input from the user.
2.Define a while loop that continues to read input until there is no more
input.
3.Within the while loop, instantiate two integer arrays s1Count and s2Count
each of length 26 to store the frequency of each character for each input
string.
4.Convert the first input string to a char array and iterate over each
character, incrementing its frequency count in the s1Count array.
5.Convert the second input string to a char array and iterate over each
character, incrementing its frequency count in the s2Count array.
6.Instantiate a StringBuilder object to store the output string.
7.Iterate over each letter of the alphabet, and for each letter, append that
letter to the StringBuilder as many times as it appears in both input strings.
8.Output the resulting string.
9.End of Program.
Uploaded Code
import java.io.BufferedReader;
import java.io.InputStreamReader;
class Main {
public static void main (String [] args) throws Exception {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s;
while ((s=br.readLine())!=null) {
int [] s1Count=new int[26];
for (char c : s.toCharArray()) s1Count[c-'a']++;
int [] s2Count=new int[26];
for (char c : br.readLine().toCharArray()) s2Count[c-'a']++;
StringBuilder sb=new StringBuilder();
for (int i=0;i<26;i++) while (s1Count[i]>0 && s2Count[i]>0) {
sb.append((char)('a'+i));
s1Count[i]--;
s2Count[i]--;
}
System.out.println(sb.toString());
}
}
}
Screen shot of accepted solution
Download