Thursday, August 29, 2013

1.1-------- check if a string has all unique characters

Q:
    implement an algorithm to determine if a string has all unique characters.

   What if you cannot use additional data structures?

A:
// (With additional structures.)

    public static boolean isUniq(String str){

        // assuming that the str chars are all ASCII character

        if (str == null && str.length()==0) return true;

        if (str.length() > 128) return false;

        int[] ascii= new int[128];

         char ch;

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

ch = str.charAt(i);

            if (ascii[ch]>0) {

                return false;

            }else{

                ascii[ch]++;

            }

        }

        return true;
    }


Mistakes:
0:  最恶心的是, 上面的128,是ASCII码的数目吗?  明明应该是256,  日啊~~~~
1: Cannot make a static reference to the non-static method isUniq(String)
    either declare an object, or  use static

2:  having a returned data type in a method declaration, you MUST return something eventually.
    Even you returned somethig earlier,  but should also return something

3: 竟然在上面,忘了取出str的各个char 的值~~~~~~~~~~~~丢人

4:if (str == null && str.length()==0) return true;
    这里,&& 后面的str   “can only be null"
    而且,这里应该用或    ||   的,  逻辑混乱。   哎~~~

5:  ascii 用boolean格式,明显比 int 要好,又不是让你数数。 哎



改进:
1:    用 bitvector 代替boolean, 只用1/8的空间。
2:   如果假设仅仅是a-z的时候,只用一个int 类型, 4*8 = 32 个bit,就可以了。
             但,书里面的移位是啥意思?












No comments:

Post a Comment