1. 程式人生 > >華為機試題

華為機試題

關聯關係:

package huawei.cn;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;

public class Main12 {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		Map<String, String> map = new LinkedHashMap<String, String>();
		Set<String> set = new TreeSet<String>();
		while (sc.hasNext()) {
			String s = sc.nextLine();
			char c = s.charAt(s.length() - 1);
			String[] sArray = s.split(",");
			String key = sArray[0].substring(1);
			set.add(key);
			String value = sArray[1].substring(0, sArray[1].length() - 1);
			map.put(key, value);
			set.add(value);
			if (c != ',') {
				break;
			}
		}
		Map<String, Boolean> result = Relation(map, set);
		int i = 0;
		Iterator<Entry<String, Boolean>> iterator = result.entrySet()
				.iterator();
		StringBuilder sb = new StringBuilder();
		
		while (iterator.hasNext()) {         
			Entry<String, Boolean> it = iterator.next();
			sb.append("{" + it.getKey() + "," + it.getValue()+ "},\n");
		}
		System.out.println(sb.toString().substring(0,sb.length()-2));
		

	}

	public static Map<String, Boolean> Relation(Map<String, String> map,
			Set<String> set) {
		Map<String, Boolean> result = new LinkedHashMap<String, Boolean>();
		for (String s : set) {
			int flag = 0;
			for (String key : map.keySet()) {
				if (s.equals(key)) {
					flag++;
				}
			}
			for (String value : map.values()) {
				if (s.equals(value)) {
					flag++;
				}
			}
			if (flag == 2) {
				result.put(s, true);
			} else {
				result.put(s, false);
			}

		}
		return result;

	}
}