Advertisement
cd62131

Print Duplication

Oct 27th, 2017
248
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.47 KB | None | 0 0
  1. import java.util.ArrayDeque;
  2. import java.util.Deque;
  3. import java.util.Scanner;
  4.  
  5. public class Duplicate {
  6.   public static void main(String[] args) {
  7.     String source = "1 2 2 2 3 3 4 4 4 5 2 2 2";
  8.     m1(source);
  9.     m2(source);
  10.   }
  11.  
  12.   private static void m1(String source) {
  13.     Scanner in = new Scanner(source);
  14.     Deque<String> not_duplicate = new ArrayDeque<>();
  15.     Deque<String> duplicate = new ArrayDeque<>();
  16.     while (in.hasNextInt()) {
  17.       String current = Integer.toString(in.nextInt());
  18.       if (not_duplicate.isEmpty() || !current.equals(not_duplicate.getLast())) {
  19.         not_duplicate.addLast(current);
  20.         continue;
  21.       }
  22.       if (duplicate.isEmpty() || !current.equals(duplicate.getLast())) {
  23.         duplicate.addLast(current);
  24.         continue;
  25.       }
  26.     }
  27.     in.close();
  28.     System.out.println(String.join(" ", duplicate));
  29.   }
  30.  
  31.   private static void m2(String source) {
  32.     Scanner in = new Scanner(source);
  33.     String out = "";
  34.     Integer prev = null;
  35.     Integer last_printed = null;
  36.     while (in.hasNextInt()) {
  37.       int current = in.nextInt();
  38.       if (prev == null || current != prev) {
  39.         prev = current;
  40.         continue;
  41.       }
  42.       if (last_printed == null || current != last_printed) {
  43.         if (last_printed != null) {
  44.           out += " ";
  45.         }
  46.         out += current;
  47.         last_printed = current;
  48.         continue;
  49.       }
  50.     }
  51.     in.close();
  52.     System.out.println(out);
  53.   }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement