Advertisement
dentia

Longest Odd-Even Sequence

Jun 17th, 2014
358
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.43 KB | None | 0 0
  1. package _27ExamPreparation;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Scanner;
  5. import java.util.regex.Matcher;
  6. import java.util.regex.Pattern;
  7.  
  8. public class _03task {
  9.     public static void main(String[] args) {
  10.         Scanner in = new Scanner(System.in);
  11.         String input = in.nextLine();
  12.         ArrayList<Integer> al = new ArrayList<Integer>();
  13.  
  14.         Pattern pat = Pattern.compile("\\d+");
  15.         Matcher match = pat.matcher(input);
  16.         while (match.find()) {
  17.             int number = Integer.parseInt(match.group());
  18.             al.add(number);
  19.         }
  20.  
  21.         Integer[] numbers = al.toArray(new Integer[0]);
  22.  
  23.         String lastState;
  24.         if (numbers[0] == 0)
  25.             lastState = "zero";
  26.         else if (numbers[0] % 2 == 0)
  27.             lastState = "even";
  28.         else
  29.             lastState = "odd";
  30.  
  31.         int maxLength = 1;
  32.         int tempLength = 1;
  33.  
  34.         for (int i = 1; i < numbers.length; i++) {
  35.             if (numbers[i] == 0) {
  36.                 if (lastState.equals("odd"))
  37.                     lastState = "even";
  38.                 else if (lastState.equals("even"))
  39.                     lastState = "odd";
  40.                 ++tempLength;
  41.             } else if (numbers[i] % 2 == 0) {
  42.                 if (lastState.equals("odd") || lastState.equals("zero"))
  43.                     ++tempLength;
  44.                 else
  45.                     tempLength = 1;
  46.                 lastState = "even";
  47.             } else if (numbers[i] % 2 == 1) {
  48.                 if (lastState.equals("even") || lastState.equals("zero"))
  49.                     ++tempLength;
  50.                 else
  51.                     tempLength = 1;
  52.                 lastState = "odd";
  53.             }
  54.             if(tempLength>maxLength) maxLength = tempLength;
  55.         }
  56.         System.out.println(maxLength);
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement