Sort the input character array | CareerCup
Sort the input character array based on the dictionary given.
For eg:, If input word is "SHEEP", sorting will make it as "EEHPS".
But in the dictionary, E may not be at first. As per the dictionary, if P is first, S followed and E later and finally H.
Then sorted array is "PSEEH".
--It's better if just store count of the character in the map
This would only work if all character is in the dict.
Read full article from Sort the input character array | CareerCup
Sort the input character array based on the dictionary given.
For eg:, If input word is "SHEEP", sorting will make it as "EEHPS".
But in the dictionary, E may not be at first. As per the dictionary, if P is first, S followed and E later and finally H.
Then sorted array is "PSEEH".
--It's better if just store count of the character in the map
public String sortByD(String s, List<Char> dict){
String output = "";
HashMap<Char, String> map = new HashMap<Char, String>();
for (Char c : dict)
m.put(c,"");
for (int i = 0; i < s.length(); ++i)
m.put(s.charAt(i),m.get(s.charAt(i))+s.charAt(i));
for (Char c : dict)
output += m.get(c);
return output;
}
http://algorithmsgeek.blogspot.com/2013/07/algo49-sort-input-character-array-based.htmlThis would only work if all character is in the dict.
16 | char order[26]; |
17 |
18 | void generateOrder( char dict[]) |
19 | { |
20 | int i=0; |
21 | for (i=0;i<26;i++) |
22 | { |
23 | order[ dict[i] - 'a' ] = i; |
24 | } |
25 | } |
26 | int position( char x) |
27 | { |
28 | return order[x- 'a' ]; |
29 | } |
30 | int cmpfunc( const void *a, const void *b) |
31 | { |
32 | return position( *( char *)a) - position (*( char *)b ); |
33 | } |
34 | int main( void ) { |
35 |
36 | char dict[26] = { 'p' , 'a' , 'b' , 'd' , 'e' , |
37 | 'f' , 'g' , 'h' , 'i' , 'j' , |
38 | 'k' , 'l' , 'm' , 'n' , 'o' , |
39 | 'c' , 'q' , 'r' , 's' , 't' , |
40 | 'u' , 'v' , 'w' , 'x' , 'y' , |
41 | 'z' }; |
42 |
43 |
44 | generateOrder(dict); |
45 |
46 | char str[5] = { 's' , 'h' , 'e' , 'e' , 'p' }; |
47 | qsort (str,SIZEOF(str), sizeof ( char ),cmpfunc); |
48 | int i; |
49 | for (i=0;i<5;i++) |
50 | { |
51 | printf ( "%c" ,str[i]); |
52 | } |
53 |
54 | return 0; |
55 | } |
Read full article from Sort the input character array | CareerCup