157. Unique Characters 【LintCode by java】

Description

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?

        解题:题目要求判断字符串是否有重复的元素,并且要求最好不用其他的数据结构,比如集合什么的。这个题目如果用HashMap来做还是挺容易的,假如没有最后那个要求,我们可以怎么做。可以申请一个布尔型的HashMap,再将字符串中的字符当做key值一个一个放进哈希表里,放之前先判断有没有这个元素,如果有的话,说明有重复的元素,返回false。循环结束,则返回true。代码如下:

public class Solution {
    /*
     * @param str: A string
     * @return: a boolean
     */
    public boolean isUnique(String str) {
        // write your code here
        Map map=new HashMap();
        for (int i = 0; i < str.length() ; i++){
            char temp=str.charAt(i);
            if(map.containsKey(temp))
                return false;
            else
                map.put(temp,i);
        }
        return true;
    }
}

如果不用hash表,只用数组也是可以实现的。不过只是针对在ASCII表范围内的字符串,也就是说输入中文字符是无效的。申请大小为256的数组,下标和ASCII表中的字符一一对应,思路与上面的差不多。代码如下:

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

猜你喜欢

转载自www.cnblogs.com/phdeblog/p/9124783.html