Advertisement
TheLima

StackOverflow - Q13348701

Nov 13th, 2012
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.23 KB | None | 0 0
  1. package stackoverflow;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.HashSet;
  5. import java.util.List;
  6. import java.util.Set;
  7.  
  8. /**
  9.  * @author TheLima
  10.  */
  11. public class Q_13348701 {
  12.  
  13.     /**
  14.      * @param args the command line arguments
  15.      */
  16.     public static void main(String[] args) {
  17.         String[] tests = {
  18.             "11,22,33", //valid.
  19.             "11,22,11", //not valid.
  20.             "Nice,Code,Brian", //Flexible version of @Brian's - valid.
  21.             "No,Means,No" //Flexible version of @Brian's - not valid.
  22.         };
  23.  
  24.         System.out.println("My own initial method:");
  25.         for (String s : tests) {
  26.             System.out.println(isValid(s));
  27.         }
  28.         System.out.println();
  29.         System.out.println("Modified Brian's \"Set method\":");
  30.         for (String s : tests) {
  31.             System.out.println(isValid_SetMethod(s));
  32.         }
  33.     }
  34.  
  35.     public static boolean isValid(String source) {
  36.         List<String> list = new ArrayList<String>();
  37.         for (String sub : source.split(",")) {
  38.             if (list.contains(sub)) {
  39.                 return false;
  40.             } else {
  41.                 list.add(sub);
  42.             }
  43.         }
  44.         return true;
  45.     }
  46.  
  47.     public static boolean isValid_SetMethod(String source) {
  48.         Set<String> set = new HashSet<String>();
  49.         for (String sub : source.split(",")) {
  50.             if (!set.add(sub)) {
  51.                 return false;
  52.             }
  53.         }
  54.         return true;
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement