13 iunie 2024

Probleme Strings

#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.

class Solution {
    public int firstUniqChar(String str) {
        Map<Character,Integer> map = new HashMap<>();
        for (int i=0; i<str.length(); i++) {
            Integer count = map.get(str.charAt(i));
            map.put(str.charAt(i), count == null ? 1 : count + 1);
        }
        for (int i=0; i<str.length(); i++) {
            if (map.get(str.charAt(i)) == 1) {
                return i;
            }
        }
        return -1;
    }

    public int firstUniqChar_2(String str) { // str contains only lowercase letters 'a' t o 'z'
        int bitVector = 0;
        int unique = (int) Math.pow(2, 27) - 1; // 1....1 for 26 bits corresponding to 'a' to 'z'
        for (int i=0; i<str.length(); i++) {
            int index = str.charAt(i) - 'a';
            if ((bitVector & (1 << index)) > 0) { // if bit index already set
                unique = unique & ~(1 << index); // clear bit at index
            }
            bitVector = bitVector | (1 << index); // set bit at index
        }
        for (int i=0; i<str.length(); i++) {
            int index = str.charAt(i) - 'a';
            boolean isBitSet = (unique & (1 << index)) > 0;
            if (isBitSet) {
                return i;
            }
        }
        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: