第一个只出现一次的字符

题目描述
在一个字符串(1<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置
第一种方法:利用hashmap能有存键值对的特点,当遍历到当前字符时候,保存该字符的数量。

 public int FirstNotRepeatingChar(String str) {
        HashMap<Character,Integer> map=new HashMap<>();
        char s[]=str.toCharArray();
        for(int i=0;i<s.length;i++){
            if(map.containsKey(s[i])){
                int tmp=map.get(s[i])+1;
                map.remove(s[i]);
                map.put(s[i],tmp);
            }else {
                map.put(s[i],1);
            }
        }
        for(int i=0;i<s.length;i++){
            if(map.containsKey(s[i])&&map.get(s[i])==1){
                return i;
            }
        }
            return -1;
    }

第二种方法:借用创建一个拥有很多桶的数组,字符的ascll码为桶的编号。遍历字符串,把当前字符根据它的ascll码装入相应的桶中,桶中元素的个数会累加。

public int FirstNotRepeatingChar1(String str){
        if(str==null||str.length()==0){
            return -1;
        }
        int a[]=new int[256];//相当于拥有256个桶的数组。
        char s[]=str.toCharArray();
        for(int i=0;i<s.length;i++){//把字符串中的元素都放入桶中
            a[s[i]]++;//编号为s[i]的桶内元素的个数增加1.
        }

        for(int j=0;j<s.length;j++){
 //遍历字符串,根据字符找到桶,检查桶内的元素个数是否为1,如果是,返回当前字符的索引。
            if(a[s[j]]==1){
                return j;
            }
        }
        return -1;
    }

第三种:

//Insert one char from stringstream
    public void Insert(char ch) {
        map.put(ch, map.getOrDefault(ch, 0) + 1);
        queue.add(ch);
        while (!queue.isEmpty() && map.get(queue.peek()) > 1)
            queue.poll();
    }

    //return the first appearence once char in current stringstream
    public char FirstAppearingOnce() {
        return queue.isEmpty() ? '#' : queue.peek();
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值