Created
March 14, 2016 07:00
-
-
Save jianminchen/794ffee7726df6062a1f to your computer and use it in GitHub Desktop.
Anagram - Java code - good style - variable name, and OP enum class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
/** | |
* | |
* | |
*/ | |
public class Solution { | |
public static void main(String[] args) { | |
Scanner scanner = new Scanner(System.in); | |
int T = scanner.nextInt(); | |
scanner.nextLine(); | |
StringBuilder sb = new StringBuilder(); | |
for (int t = 0; t < T; t++) { | |
String next = scanner.nextLine(); | |
int result = doAnagramOp(next); | |
sb.append(result).append("\n"); | |
} | |
System.out.println(sb); | |
} | |
private static int doAnagramOp(String next) { | |
int length = next.length(); | |
if ((length & 1) == 1) { | |
return -1; | |
} | |
int[] letterCnt = new int[26]; | |
String strA = next.substring(0, length / 2); | |
String strB = next.substring(length / 2, length); | |
findLetterCount(strA, letterCnt, OP.PLUS); | |
findLetterCount(strB, letterCnt, OP.MINUS); | |
boolean noChange = true; | |
int twiceChangeSum = 0; | |
for (int i = 0; i < 26; i++) { | |
if (letterCnt[i] == 0) { | |
continue; | |
} else { | |
noChange = false; | |
twiceChangeSum += Math.abs(letterCnt[i]); | |
} | |
} | |
if (noChange) { | |
return 0; | |
} else { | |
return twiceChangeSum / 2; | |
} | |
} | |
private static void findLetterCount(String str, int[] letterCnt, OP op) { | |
int len = str.length(); | |
for (int i = 0; i < len; i++) { | |
int idx = str.charAt(i) - 'a'; | |
switch (op) { | |
case PLUS: | |
letterCnt[idx]++; | |
break; | |
case MINUS: | |
letterCnt[idx]--; | |
break; | |
} | |
} | |
} | |
private enum OP { | |
PLUS, MINUS; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment