程序员面试金典-面试题 01.01. 判定字符是否唯一

题目:

https://leetcode-cn.com/problems/is-unique-lcci/

实现一个算法,确定一个字符串 s 的所有字符是否全都不同。

示例 1:

输入: s = "leetcode"
输出: false
示例 2:

输入: s = "abc"
输出: true
限制:

0 <= len(s) <= 100
如果你不使用额外的数据结构,会很加分。

分析:

哈希做法,开辟数组,统计对应位置的字符出现数量,遍历字符串,当数量为1时,表示已经出现过了,有重复字符。

程序:

class Solution {
    public boolean isUnique(String astr) {
        int[] a = new int[128];
        for(char ch:astr.toCharArray()){
            if(a[ch] == 1)
                return false;
            a[ch] = 1;
        }
        return true;
    }
}

猜你喜欢

转载自www.cnblogs.com/silentteller/p/12389505.html