Skip to content

Commit 87f3645

Browse files
committed
Added the removed file
1 parent d39a782 commit 87f3645

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed

Strings/CustomSortString.java

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
/* Implementation of Custom Sort String program code using java
2+
*
3+
* You are given two strings order and str. All the words of order are unique and
4+
* were sorted in some custom order previously.
5+
6+
* Permute the characters of str so that they match the order that order was sorted.
7+
* More specifically, if a character x occurs before a character y in order, then x
8+
* should occur before y in the permuted string.
9+
10+
* Return any permutation of str that satisfies this property.
11+
*
12+
* Problem link: https://leetcode.com/problems/custom-sort-string/
13+
*
14+
*/
15+
16+
import java.util.*;
17+
import java.io.*;
18+
19+
class CustomSortString
20+
{
21+
// this function will return any permutation of str so that they match the order that
22+
// order is sorted
23+
public String customSortString(String order, String str)
24+
{
25+
int []freq =new int[26];
26+
27+
// determining the frequency of each character
28+
for(char c: str.toCharArray())
29+
freq[c-'a']++;
30+
31+
StringBuilder ans = new StringBuilder();
32+
33+
// appending the characters in order to ans
34+
for(char orderChar: order.toCharArray())
35+
{
36+
while(freq[orderChar-'a']>0)
37+
{
38+
ans.append(orderChar);
39+
freq[orderChar-'a']--;
40+
}
41+
}
42+
43+
//Adding the rest of the characters
44+
for(int i=0;i<26;i++)
45+
{
46+
int freqC = freq[i];
47+
while(freqC>0)
48+
{
49+
ans.append((char)(i+'a'));
50+
freqC--;
51+
}
52+
}
53+
// returning the resultant string
54+
return ans.toString();
55+
}
56+
57+
public static void main()
58+
{
59+
Scanner sc=new Scanner(System.in);
60+
String s = sc.next();
61+
String t = sc.next();
62+
CustomSortString obj = new CustomSortString();
63+
System.out.println(obj.customSortString(s,t));
64+
}
65+
}
66+
67+
/*
68+
* Example 1:
69+
*
70+
* Input: order = "cba", s = "abcd"
71+
* Output: "cbad"
72+
* Explanation:
73+
* "a", "b", "c" appear in order, so the order of "a", "b", "c" should be "c", "b", and "a".
74+
* Since "d" does not appear in order, it can be at any position in the returned string. "dcba", "cdba", "cbda" are also valid outputs.
75+
*
76+
* Example 2:
77+
*
78+
* Input: order = "cbafg", s = "abcd"
79+
* Output: "cbad"
80+
*
81+
* Time Complexity: O(order.length + str.length)
82+
*/

0 commit comments

Comments
 (0)