利用Stack的先进先出特性,将字符串转换为的字符挨个装入时,与最顶端的字符比较,若相同,弹出字符,该字符不装入,否则,装入字符。最后转为字符串,返回。
public String WordsMerge (String[] Words) { // write code here if (Words == null) { return ""; } Stack<Character> stack = new Stack<>(); for (int i = 0; i < Words.length; i++) { int size = Words[i].length(); for (int j = 0; j < size; j++) { if (stack.isEmpty()) stack.push(Words[i].charAt(j)); else { char x = stack.peek(); if (x != Words[i].charAt(j)) { stack.push(Words[i].charAt(j)); } else { stack.pop(); } } } } String str = ""; while (!stack.isEmpty()) { str = stack.pop() + "" + str; } return str; }