leetcode 面试01.01 判定字符是否唯一 java实现 算法初练

面试题 01.01. 判定字符是否唯一 实现一个算法,确定一个字符串 s 的所有字符是否全都不同。

示例 1:

输入: s = “leetcode”
输出: false

示例 2:

输入: s = “abc”
输出: true

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

提示信息:
试试散列表

根据提示散列表
HashMap(特性为不允许有重复的主键
泛型设置<Character,Integer>
HashMap常用方法:put(K,V) 向集合添加元素
size()获取集合长度
我的解题思路:设置计数器,初始值0,添加一次则++自增。
HashMap的put方法遇见重复的K时,会覆盖掉之前的(K,V)
所以,当重复添加就有覆盖,HashMap的长度就会比原字符串的长度

class Solution {
    public boolean isUnique(String astr) {
        boolean flag = true;	//默认无重复字符串
        int cnt = 0;
        HashMap<Character,Integer> mh = new HashMap<Character,Integer>();
        for(int i = 0;i <astr.length();i++){	//遍历字符串向mh添加元素
            char ch = astr.charAt(i);
            mh.put(ch,++cnt);
        }
        if(mh.size()<astr.length()){	//当mh的长度,小于 ,原字符串
            flag = false;				//证明有同key覆盖情况,则有重复元素
        }
        return flag;
    }
}

其他解题方法

class Solution {
    public static boolean isUnique(String astr) {
        return astr.chars().distinct().count() == astr.length();
    }
}

字符串.chars.去重.计数

IntStream java.lang.CharSequence.chars()
Returns a stream of int zero-extending the char valuesfrom this sequence. Any char which maps to a surrogate codepoint is passed through uninterpreted.
If the sequence is mutated while the stream is being read, theresult is undefined.
Returns:
an IntStream of char values from this
sequenceSince:
1.8

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值