#1. First non-repeating character
Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.
#2. Permutation of a palindrome
Given a string, return if it is a permutation of a palindrome.
class Solution {
public boolean canBecomePalindrome(String str) {
if (str.length() == 0) {
return false;
}
int bitVector = 0;
for (int i=0; i<str.length(); i++) {
int index = str.charAt(i) - 'a';
if ((bitVector & (1 << index)) > 0) { // if bit set
bitVector = bitVector & ~(1 << index); // clear
} else {
bitVector = bitVector | (1 << index); // set
}
}
// se poate transforma in palindrom daca:
// Are nr par de caractere si toti bitii 0, SAU
// nr impar de caractere si un singur bit 1
boolean evenAmountOfChar = str.length() % 2 == 0;
boolean hasBit1 = false;
for (int i=0; i<26; i++) { // 26 letters in alphabet
if ((bitVector & (1 << i)) > 0) { // if bit set
if (hasBit1) {
return false; // a second bit is set
}
hasBit1 = true;
}
}
return evenAmountOfChar ^ hasBit1;
}
}
Niciun comentariu:
Trimiteți un comentariu