Advertisement
vlastomar

Mirror words

Jul 15th, 2020
886
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. import java.util.*;
  2. import java.util.regex.Matcher;
  3. import java.util.regex.Pattern;
  4.  
  5. public class MirrorWords {
  6. public static void main(String[] args) {
  7. Scanner scan = new Scanner(System.in);
  8. LinkedHashMap<String, String> equalStrings = new LinkedHashMap<>();
  9. int count = 1;
  10. boolean check = false;
  11.  
  12. String input = scan.nextLine();
  13. Pattern patt = Pattern.compile("(@|#)(?<first>[A-Za-z]{3,})(\\1)(\\1)(?<second>[A-Za-z]{3,})(\\1)");
  14. Matcher mat = patt.matcher(input);
  15. if (!mat.find()){
  16. System.out.println("No word pairs found!");
  17. }
  18. while (mat.find()){
  19. check = true;
  20. count++;
  21. String first = mat.group("first");
  22. String second = mat.group("second");
  23. StringBuilder temp1 = new StringBuilder(second);
  24. String reversedSecond = temp1.reverse().toString();
  25. if (reversedSecond.equals(first)){
  26. equalStrings.putIfAbsent(first, "");
  27. equalStrings.put(first, second);
  28. }
  29. }
  30. if (equalStrings.isEmpty()){
  31. if (check) {
  32. System.out.println(String.format("%d word pairs found!", count));
  33. }
  34. System.out.println("No mirror words!");
  35. }else{
  36. System.out.println(String.format("%d word pairs found!", count));
  37. System.out.println("The mirror words are:");
  38. int[] counter = {1};
  39. equalStrings
  40. .entrySet()
  41. .forEach(f -> {
  42. System.out.print(String.format("%s <=> %s", f.getKey(), f.getValue()));
  43. if (counter[0] < equalStrings.size()){
  44. System.out.print(", ");
  45. }
  46. counter[0]++;
  47. });
  48. }
  49. }
  50.  
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement