前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【LeetCode程序员面试金典】面试题 01.01. Is Unique LCCI

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

作者头像
韩旭051
发布2020-06-22 17:07:53
3070
发布2020-06-22 17:07:53
举报
文章被收录于专栏:刷题笔记刷题笔记

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数组实现

代码语言:javascript
复制
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位 进行存储

代码语言:javascript
复制
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

代码语言:javascript
复制
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)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-05-11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 哈希表思想
  • 优化 用int 的 26位 进行存储
  • 其他思路 用哈希map
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档