【LeetCode程序员面试金典】面试题 01.01. Is Unique LCCI

判断字符串是否全由唯一字符组成
本文介绍了一种算法,用于判断一个字符串的所有字符是否唯一。提供了三种方法:使用布尔数组、利用整数的位操作以及借助哈希集合。这三种方法避免了额外的数据结构,实现了高效判断。

Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures?

Example 1:

Input: s = "leetcode"
Output: false
Example 2:

Input: s = "abc"
Output: true

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/is-unique-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

哈希表思想

java数组实现

class Solution {
    public boolean isUnique(String astr) {
        boolean[] num = new boolean[26];
        Arrays.fill(num,true);
        for(int i = 0;i < astr.length();i++){
            if (num[astr.charAt(i)-'a'] == true){
                num[astr.charAt(i)-'a'] = false;
            }else{
                return false;
            }
        }
        return true;
    }
}

优化 用int 的 26位 进行存储

class Solution {
    public boolean isUnique(String astr) {
        int mark = 0;
        for(int i = 0;i < astr.length();i++){
            int bit = 1 << (astr.charAt(i) - 'a');
            if ((mark & bit) == 0) {
                mark |= bit;
            } else {
                return false;
            }
        }
        return true;
    }
}

其他思路 用哈希map

class Solution {
    public boolean isUnique(String astr) {
        Set set = new HashSet();
        for (int i = 0; i <astr.length() ; i++) {
            set.add(astr.charAt(i));
        }
        return set.size() == astr.length(); 
    }
}

作者:evelynnnnn
链接:https://leetcode-cn.com/problems/is-unique-lcci/solution/javali-yong-setqu-zhong-by-evelynnnnn/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码不停Ti

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值