arunbabuasp
BAN USERimport java.util.HashMap;
import java.util.Map.Entry;
public class CountPalindrome {
public static void main(String[] args) {
String input = "neveroddoreven";
CountPalindrome cp = new CountPalindrome();
char[] inpChars = new char[input.length()];
input.getChars(0, input.length(), inpChars, 0);
System.out.println(cp.countPalinAnags(inpChars));
}
public int countPalinAnags(char[] inp) {
HashMap<Character, Integer> hm = new HashMap<Character, Integer>();
for (int i = 0; i < inp.length; i++) {
Integer val = hm.get(inp[i]);
if (null == val)
hm.put(inp[i], 1);
else
hm.put(inp[i], val + 1);
}
int oddCharCnt = 0;
int mirrCnt = 0;
int denom = 1;
for(Entry<Character, Integer> e : hm.entrySet()) {
int n = e.getValue();
if (n % 2 != 0)
oddCharCnt++;
if (oddCharCnt > 1)
return 0;
n /= 2;
e.setValue(n);
mirrCnt += n;
denom *= factorial(n);
}
return factorial(mirrCnt) / denom;
}
private int factorial(int n) {
int res = 1;
while (n > 0) {
res *= n;
n -= 1;
}
return res;
}
}
Used List.get in place of getItemAt in below answer
import java.util.LinkedList;
import java.util.List;
public class ZeroToOne {
public static void main(String[] args) {
int zero = 1000; //Zero count
int one = 9; //One Count
List<Integer> list = new LinkedList<>();
ZeroToOne zto = new ZeroToOne();
for (int i = 0; i < zero; i++)
list.add(0);
for (int i = 0; i < one; i++)
list.add(1);
System.out.println(zto.getZeroToOnePos(list));
}
public int getZeroToOnePos(List<Integer> list) {
int start = 0;
int end = 0;
int factor = 2;
/*
* Narrow down search area by exponential movements and
* adjust end point if gone beyond original list.
*/
while(true) {
/*
* try-catch to check if gone beyond list.
* In case of c, we can check for value != 0 and 1
*/
try {
if(list.get(end) == 1)
break;
start = end + 1;
end += factor;
factor *= 2;
} catch(Exception e) {
//Assuming IndexOutOfBounds or similar
/*
* Went beyond the list boundary. Re-align end position
*/
factor = (end - start) / 2;
end = start + factor;
if (start == end)
return end + 1;
}
}
/*
* Binary search for 0-1 in identified range.
*/
while (true) {
if (start >= end)
return end;
int middle = (start + end) / 2;
int val = list.get(middle);
if (1 == val) {
if (list.get(middle - 1) != 1) // can be a '== 0' check also
return middle;
else
end = middle - 1;
} else {
start = middle + 1;
}
}
}
}
1. Sort the characters in each word in the dictionary and use that as key to add in HashMap with value as linked list in which we need to add words as they are.
- arunbabuasp July 07, 20132. Sort the characters in 'given word' and using that as key retrieve the linked list from above HashMap.
3. Print the contents of above linked list.