https://sites.google.com/site/codingbughunter/algorithm-question-discuss
Given two String arrays, one array has the equal relation of any two element, another one has not equal relation.
Like below:
arr1 ={{A,B}{B,C}...} means {“A=B”, "B=C", ...} arr2 = {{A,C}{F,R}} means {"A!=C", "F!=R", ...}Judge if there is a conflict in this two arrays.
判断是否有矛盾,这个例子就有矛盾:A!=C given提取元素的method: getID(..),这个不用自己写:String[] sarr = getID(arr1 [0]) --> sarr {A, B}
It works, but not efficient.
public static void main(String[] args){ String[][] and = new String[][]{{"a","b"},{"a","c"},{"a","m"}}; String[][] not = new String[][]{{"a","y"},{"c","b"},{"n","m"}}; System.out.println("res : "+isRight(and,not)); } public static boolean isRight(String[][] and, String[][] not){ ArrayList<HashSet<String>> list = new ArrayList<HashSet<String>>(); for(String[] val : and){ if(list.isEmpty()){ HashSet<String> table = new HashSet<String>(); table.add(val[0]); table.add(val[1]); list.add(table); }else{ for( HashSet<String> tmp : list){ if(tmp.contains(val[0]) || tmp.contains(val[1])){ tmp.add(val[0]); tmp.add(val[1]); continue; } } HashSet<String> next = new HashSet<String>(); next.add(val[0]); next.add(val[1]); list.add(next); } } for(String[] val : not){ for(HashSet<String> tmp : list){ if(tmp.contains(val[0]) && tmp.contains(val[1])){ return false; } } } return true; }