fork download
  1. import java.util.*;
  2.  
  3. class Main {
  4. public static void main(String[] args) {
  5. String[] text = {"code", "doce", "ecod", "framer", "frame"};
  6. int n = text.length;
  7.  
  8. Stack<String> st = new Stack<>();
  9. st.push(text[0]);
  10.  
  11. for (int i = 1; i < n; i++) {
  12. if (!isAnagram(st.peek(), text[i])) {
  13. st.push(text[i]);
  14. }
  15. }
  16.  
  17. String[] ans = new String[st.size()];
  18. int idx = ans.length - 1;
  19. while (!st.isEmpty()) {
  20. ans[idx--] = st.pop();
  21. }
  22.  
  23. for (String s : ans) {
  24. System.out.println(s);
  25. }
  26. }
  27.  
  28. public static boolean isAnagram(String s, String t) {
  29. if (s.length() != t.length()) {
  30. return false;
  31. }
  32. int[] countChar = new int[26];
  33. for (char c : s.toCharArray()) {
  34. countChar[c - 'a']++;
  35. }
  36. for (char c : t.toCharArray()) {
  37. countChar[c - 'a']--;
  38. if (countChar[c - 'a'] < 0) {
  39. return false;
  40. }
  41. }
  42. return true;
  43. }
  44. }
  45.  
Success #stdin #stdout 0.11s 54524KB
stdin
Standard input is empty
stdout
code
framer
frame