-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathS.java
More file actions
87 lines (77 loc) · 2.35 KB
/
S.java
File metadata and controls
87 lines (77 loc) · 2.35 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import java.io.*;
import java.util.*;
public class S
{
static ArrayList<TreeNode> in;
static class TreeNode {
char letter;
int freq;
TreeNode left,right;
TreeNode(char l,int f) {
letter=l;
freq=f;
}
}
public static TreeNode insert(TreeNode root, TreeNode target) {
if(root==null)
return target;
if(target.freq>root.freq)
root.left=insert(root.left,target);
else if(target.freq<root.freq)
root.right=insert(root.right,target);
else if(target.freq==root.freq) {
if(target.letter<root.letter)
root.left=insert(root.left,target);
else {
root.right=insert(root.right,target);
}
}
return root;
}
public static void inorder(TreeNode root) {
if(root==null)
return;
inorder(root.left);
in.add(root);
inorder(root.right);
}
public static int[] bucket(String s)
{
int[] buc=new int[26];
for(int i=0;i<s.length();i++) {
if(s.charAt(i)==' ')
continue;
buc[s.charAt(i)-'a']++;
}
return buc;
}
public static void main(String[] args) throws IOException
{
BufferedReader reader = new BufferedReader(new FileReader("letter_frequencies.in"));
BufferedWriter writer = new BufferedWriter(new FileWriter("p.out"));
int numCases = Integer.parseInt(reader.readLine());
int caseNum=1;
while(caseNum<=numCases) {
String s=reader.readLine();
int[] buc=bucket(s);
TreeNode root=null;
for(int i=0;i<buc.length;i++) {
if(buc[i]>0) {
char letter=(char)(i+'a');
int freq=buc[i];
TreeNode n=new TreeNode(letter,freq);
root=insert(root,n);
}
}
in=new ArrayList<TreeNode>();
inorder(root);
writer.write("Case #" + (caseNum++) + "\n");
for(int j=0;j<in.size();j++) {
TreeNode t=in.get(j);
writer.write(t.letter+" "+t.freq+"\n");
}
}
writer.close();
reader.close();
}
}