题意:字处理程序检查输入的单词是否正确。若不正确,则按照规则在字典中找与该单词相近的单词。
解题思路:按照题目给出的规则模拟。
要点:要注意查找效率,遍历会超时。此处用的是TreeMap,查找效率log2(N)。
代码
1import java.io.*;
2import java.util.*;
3class Main
4{
5 private static TreeMap<String, Integer> dic = new TreeMap<String, Integer>();
6 private static TreeSet<MyNode> nodes = new TreeSet<MyNode>();
7 private static char[] alp = {
8 'a', 'b', 'c', 'd', 'e', 'f', 'g',
9 'h', 'i', 'j', 'k', 'l', 'm', 'n',
10 'o', 'p', 'q', 'r', 's', 't',
11 'u', 'v', 'w', 'x', 'y', 'z',
12 };
13 public static void main(String[] args)
14 {
15
16 Scanner sc = new Scanner(System.in);
17 String strt = sc.nextLine();
18 int count = 0;
19 while(!"#".equals(strt))
20 {
21 dic.put(strt, count++);
22 strt = sc.nextLine();
23 }
24 strt = sc.nextLine();
25 while(!"#".equals(strt))
26 {
27 if(dic.get(strt) != null)
28 {
29 System.out.println(strt + " is correct");
30
31 }
32 else{
33 nodes.clear();
34 rule1(strt);
35 rule2(strt);
36 rule3(strt);
37 System.out.print(strt + ":");
38
39 Iterator<MyNode> it = nodes.iterator();
40 while(it.hasNext())
41 {
42 MyNode nd = it.next();
43 System.out.print(" " + nd.getStr());
44
45 }
46 System.out.println();
47
48
49 }
50
51 strt = sc.nextLine();
52 }
53 }
54 private static void rule1(String strt)
55 {
56
57 char[] charArry = strt.toCharArray();
58 for(int i = 0; i < charArry.length; i++)
59 {
60 String str2 = new String(charArry, 0, i) +
61 new String(charArry, i + 1, charArry.length - i - 1);
62
63 Integer p = dic.get(str2);
64 if(p != null)
65 {
66 nodes.add(new MyNode(str2, p));
67 }
68 else if(strt.length() == 1)
69 {
70 for(int j = 0; j < alp.length; j++)
71 {
72 p = dic.get("" + alp[j]);
73 if(p != null)
74 nodes.add(new MyNode("" + alp[j], p));
75 }
76 }
77
78 }
79 }
80
81 private static final void rule2(String strt)
82 {
83 char[] charArry = strt.toCharArray();
84 for(int i = 0; i < charArry.length; i++)
85 {
86 for(int j = 0; j < alp.length; j++)
87 {
88 char c = charArry[i];
89 charArry[i] = alp[j];
90 String str2 = new String(charArry);
91 Integer p = dic.get(str2);
92 if(p != null)
93 {
94 nodes.add(new MyNode(str2, p));
95 }
96
97 charArry[i] = c;
98 }
99 }
100 }
101
102 private static void rule3(String strt)
103 {
104 StringBuffer buf = new StringBuffer();
105 char[] charArry = strt.toCharArray();
106 for(int i = 0; i <= charArry.length; i++)
107 {
108 for(int j = 0; j < alp.length; j++)
109 {
110
111 String str2 = new String(charArry, 0, i) + alp[j]
112 + new String(charArry, i, charArry.length - i);
113 Integer p = dic.get(str2);
114 if(p != null)
115 {
116 nodes.add(new MyNode(str2, p));
117 }
118 }
119 }
120 }
121}
122
123/**//*
124*/
125class MyNode implements Comparable<MyNode>
126{
127 private String str;
128 private int p;
129 MyNode(String str, int p)
130 {
131 this.str = str;
132 this.p = p;
133 }
134 public String getStr()
135 {
136 return str;
137 }
138 public int compareTo(MyNode n2){
139 return this.p - n2.p;
140 }
141}
142
143
posted on 2013-04-09 15:17
小鼠标 阅读(133)
评论(0) 编辑 收藏 引用 所属分类:
Java基础练习