【华为OJ】【073-查找兄弟单词】
2016-05-17 07:51
459 查看
【华为OJ】【算法总篇章】
【华为OJ】【073-查找兄弟单词】
【工程下载】
题目描述
输入描述
先输入字典中单词的个数,再输入n个单词作为字典单词。 输入一个单词,查找其在字典中兄弟单词的个数 再输入数字n
输出描述
根据输入,输出查找到的兄弟单词的个数
输入例子
3 abc bca cab abc 1
输出例子
2 bca
算法实现
import java.util.*; /** * Author: 王俊超 * Date: 2016-01-05 14:49 * All Rights Reserved !!! */ public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Scanner scanner = new Scanner(Main.class.getClassLoader().getResourceAsStream("data.txt")); Map<Key, List<String>> map = new HashMap<>(); while (scanner.hasNext()) { map.clear(); int n = scanner.nextInt(); // 构造一个字典 while ((--n) >= 0) { String s = scanner.next(); Key k = new Key(s); if (map.containsKey(k)) { map.get(k).add(s); } else { List<String> list = new ArrayList<>(); list.add(s); map.put(k, list); } } // String s = scanner.next(); // s的第i个兄弟节点 int i = scanner.nextInt(); Key k = new Key(s); List<String> list = map.get(k); if (list != null) { Collections.sort(list); // 删除s while (list.contains(s)) { list.remove(s); } System.out.println(list.size()); int cnt = 0; Iterator<String> itr = list.iterator(); String t = ""; while (cnt < i && itr.hasNext()) { t = itr.next(); if (!t.equals(s)) { cnt++; if (cnt == i) { System.out.println(t); } } } }else { System.out.println(0); } } scanner.close(); } private static class Key { private String s; private String t; private int hashCode; public Key(String s) { this.s = s; if (s == null) { hashCode = 0; } else { char[] chars = s.toCharArray(); Arrays.sort(chars); t = new String(chars); hashCode = t.hashCode(); } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Key key = (Key) o; return t != null ? t.equals(key.t) : key.t == null; } @Override public int hashCode() { return hashCode; } } }
相关文章推荐
- 微软.NET 正式劈腿成功,横跨所有平台
- [置顶] eclipse对hibernate使用逆向工程
- spring boot整合Morphia对MongoDB进行操作
- 好久不见的电信强制广告又来了。
- 并非目不转睛的404网页
- 5、Gerrit权限控制
- ArcGIS Runtime 本地API介绍
- 一位私募操盘手写给亏钱散户的信(句句都是良心话!)
- 【华为OJ】【072-火车进站】
- [绍棠] 利用CocoaHTTPServer实现WIFI局域网传输文件到iPhone, 实现文件上传
- 第8周 C语言及程序设计提高例程-30 字符和字符串处理函数
- LeetCode 267. Palindrome Permutation II
- throws和throw的区别
- 【华为OJ】【071-公共子串计算】
- bestcoder.hdu.edu.cn
- bzoj3573: [Hnoi2014]米特运输
- C#多线程
- 互联网服务端技术——如何学(下B)
- HTTP HSTS协议和 nginx
- Java设计模式(一) 简单工厂模式不简单