Unique String

April 16, 2018 —

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import java.util.Map;
import java.util.HashMap;

class UniqueString {

    private static Boolean uniqueUsingMap (String string) {

        Map<Character, Character> map = new HashMap<>();

        for (char ch : string.toCharArray()) {
            if (map.containsKey(ch))
            return false;
            map.put(ch, ch);
        }
        return true;

    }

    private static Boolean uniqueUsingBit (String string) {

        int integer = 0;

        for (int i = 0; i < string.length(); i++) {

            if ((integer & (1 << 'a' - string.charAt(i))) != 0)
                return false;

            integer = integer | (1 << 'a' - string.charAt(i));
        }

        return true;

    }

    public static void main (String args[]) {
        if (args.length > 0)
        System.out.println("is unique? : " + uniqueUsingBit(args[0]).toString());
        else
        System.out.println("Please re-run with a String");
    }

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#!/usr/bin/env python3

class UniqueString():

    def __init__(self, string = "world"):
        self.string = string;

    def by_bits(self):
        integer = 0;
        for char in self.string:
            print (char)
            if (integer & (1 << abs(ord('a') - ord(char)))) != 0:
                return False
            integer = integer | (1 << abs(ord('a') - ord(char)))
        return True

    def by_set(self):
        chars = set()
        for char in self.string:
            print(char)
            if char in chars:
                return False
            chars.add(char)
        return True

def main():
    us = UniqueString()
    # print (us.by_bits())
    print (us.by_set())

if __name__ == "__main__":
    main()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#!/usr/bin/env ruby

class UniqueString
    def initialize (word="World")
        @word = word
    end

    def by_bit
        integer = 0

        @word.split(//).each do |char|
            puts char
            if (integer & (1 << ('a'.ord - char.ord).abs)) != 0
                return false
            end
            integer = integer | (1 << ('a'.ord - char.ord).abs)
        end
        return true
    end
    
    def by_list
        chars = Array.new
        @word.split(//).each do |char|
            if chars.include? char
                return false
            end
            chars.push(char)
        end
        return true
    end
end

if __FILE__ == $0
    us = UniqueString.new()
    puts us.by_bit
end