不准访问
- 积分
- 105
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2013-6-16
- 最后登录
- 1970-1-1
|
不知道这样是不是满足题目了? 写得有点挫..
- public static class TrieNode {
- char ch;
- boolean isString;
- HashMap<Character, TrieNode> hm;
- int wordCount;
- public TrieNode() {
- this.isString = false;
- this.wordCount = 0;
- hm = new HashMap<>();
- }
- }
- public static class Trie {
- TrieNode root;
- public Trie() {
- root = new TrieNode();
- }
- public void insert(String s) {
- TrieNode curNode = this.root;
- for (int i=0; i<s.length(); i++) {
- char curCh = s.charAt(i);
- if (!curNode.hm.containsKey(curCh)) curNode.hm.put(curCh, new TrieNode());
- curNode = curNode.hm.get(curCh);
- curNode.ch = curCh;
- curNode.wordCount++;
- }
- }
- public String comparess(String s) {
- StringBuilder sb = new StringBuilder();
- TrieNode curNode = this.root;
- TrieNode pre = this.root;
- boolean stop = false;
- boolean allOne = true;
- for (int i=0; i<s.length(); i++) {
- char curCh = s.charAt(i);
- curNode = pre.hm.get(curCh);
- if (curNode.wordCount > 1) allOne = false;
- if (curNode.wordCount < pre.wordCount) {
- stop = true;
- sb.append(curCh);
- }
- else if (!stop) sb.append(curCh);
- pre = curNode;
- }
- sb.append(s.length()).append(curNode.ch);
- return allOne ? s.substring(0, 1)+s.length()+s.substring(s.length()-1) : sb.toString();
- }
- }
- public static void main(String[] args) {
- // write your code here
- String[] arr = new String[]{"like", "god", "internal", "me", "internet", "interval", "intension", "face", "intrusion"};
- abbreviation(arr);
- System.out.print("\n");
- arr = new String[]{"interval", "internal", "intaaaal"};
- abbreviation(arr);
- System.out.print("\n");
- arr = new String[]{"interval", "internal"};
- abbreviation(arr);
- System.out.print("\n");
- arr = new String[]{"aaa"};
- abbreviation(arr);
- System.out.print("\n");
- arr = new String[]{};
- abbreviation(arr);
- System.out.print("\n");
- }
- public static void abbreviation(String[] arr) {
- HashMap<String, Trie> group = new HashMap<>();
- for (String s : arr) {
- String key = s.substring(0, 1)+s.length()+s.substring(s.length()-1);
- if (!group.containsKey(key)) group.put(key, new Trie());
- group.get(key).insert(s);
- }
- for (String s : arr) {
- String key = s.substring(0, 1)+s.length()+s.substring(s.length()-1);
- String compressWord = group.get(key).comparess(s);
- if (compressWord.length() >= s.length()) System.out.print(s+" ");
- else System.out.print(compressWord+" ");
- }
- }
复制代码 |
|