[Lintcode 1 easy]Unique Characters

【Problem】

Unique Characters

Implement an algorithm to determine if a string has all unique characters.

 
Example

Given "abc", return true.

Given "aab", return false.

Challenge

What if you can not use additional data structures?

---------------------------------------------------------------------------------------------------------------------

 

This problem is from <crack the coding interview>.

 

It is used to test the basic knowledge of ASCII.

If we didn't care about how much space we used, basic idea is to set a flag for every single char in the string. If the char has appeared once, return false.

Following is the code:

public class Solution {
    /**
     * @param str: a string
     * @return: a boolean
     */
    public boolean isUnique(String str) {
        
        // write your code here
        if(str.length()>128) return false;
        
        boolean[] char_set= new boolean[256];
        for(int i=0;i<str.length();i++)
        {
            int val=str.charAt(i);
            if(char_set[val])
            {
                return false;
            }
            else
            {
                char_set[val]=true;
            }
        }
        return true;
       
    }
}

 

 

 

posted on 2015-11-05 03:00  一心一念  阅读(213)  评论(0编辑  收藏  举报

导航