knomo

TopCoder Practice "AB"

Jan 8th, 2016 (edited)
216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.05 KB | None | 0 0
  1. public class StringAB {
  2.  
  3.     private static final String STR_A = "A";
  4.     private static final String STR_B = "B";
  5.     public static final char CHAR_B = 'B';
  6.     public static final char CHAR_A = 'A';
  7.  
  8.     public static void main(String[] args) {
  9.         String s = generateStringNK(5, 8);
  10.         System.out.println(s);
  11.         System.out.println(countABPoints(s, s.length()));
  12.     }
  13.  
  14.     private static String generateStringNK(int N, int K){
  15.         int aCount = N / 2;
  16.         int bCount = N % 2 == 0 ? aCount : aCount + 1;
  17.         int maxK = aCount * bCount;
  18.  
  19.         if (K > maxK) return "";
  20.  
  21.         StringBuilder sb = new StringBuilder();
  22.         for (int i = 0; i < aCount; ++i) sb.append(STR_A);
  23.         for (int i = 0; i < bCount; ++i) sb.append(STR_B);
  24.         String s = sb.toString();
  25.  
  26.         for (int i = countABPoints(s, N); i > K; --i) s = swapABForDecrement(s, N);
  27.  
  28.         return s;
  29.     }
  30.  
  31.     private static int countABPoints(String s, int n) {
  32.         int bCount = 0;
  33.         int sum = 0;
  34.         for (int i = n - 1; i > -1; --i) {
  35.             if(s.charAt(i) == CHAR_A) {
  36.                 sum += bCount;
  37.             } else {
  38.                 ++bCount;
  39.             }
  40.         }
  41.         return sum;
  42.     }
  43.  
  44.     private static String swapABForDecrement(String s, int n) {
  45.         int index = getIndexOfAAfterLastSubstringOfB(s, n);
  46.         char[] charArray = s.toCharArray();
  47.         charArray[index] = CHAR_B;
  48.         charArray[index + 1] = CHAR_A;
  49.         return new String(charArray);
  50.     }
  51.  
  52.     private static int getIndexOfAAfterLastSubstringOfB(String s, int n) throws IndexOutOfBoundsException {
  53.         int indexOfLastB = getIndexOfLastB(s, n);
  54.         while (true) {
  55.             --indexOfLastB;
  56.             if (s.charAt(indexOfLastB) == CHAR_A) return indexOfLastB;
  57.         }
  58.     }
  59.  
  60.     private static int getIndexOfLastB(String s, int n) {
  61.         int indexOfLastB = n;
  62.         do {
  63.             --indexOfLastB;
  64.         } while (s.indexOf(STR_B, indexOfLastB) == -1);
  65.         return indexOfLastB;
  66.     }
  67.  
  68.  
  69. }
Advertisement
Add Comment
Please, Sign In to add comment