leetcode面试题50

一、题目

在字符串 s 中找出第一个只出现一次的字符。如果没有,返回一个单空格。 s 只包含小写字母。

示例 1:
输入:s = "abaccdeff"
输出:'b'
示例 2:
输入:s = "" 
输出:' '
限制:

0 <= s 的长度 <= 50000

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/di-yi-ge-zhi-chu-xian-yi-ci-de-zi-fu-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

二、解决方法:

这里可以使用new int[26],也就是我们所说的数组表示,但实际上,当重复次数超过2的时候,再累积已经没有任何意义了,所以才有了如下的解决思路:

(1)以bit位表示当前第i个数出现了;

(2)firstAppear表示该数第一次出现,repeat表示第二次出现;

(3)根据firstAppear & (1 << index)来判断,当前位置是否已经出现过该字母;index是字母的ASCII码 - 'a'(大写为ASCII码 - 'A');

(4)如果firstAppear & (1 << index) > 0(注意,一定是大于0,不一定等于1),那就表示出现过了,repeat的相应bit位置1;

(5)第二次判断时,给出一个index,判断是否存在firstAppear & (1 << index) > 0且(repeat & (1 << index)) == 0的情况,该状态对应的字符即为结果;

class Solution {

    // 大写字母
    int upperfirstAppear = 1 << 26;
    int upperRepeat = 1 << 26;
    // 小写字母    
    int firstAppear = 1 << 26;
    int repeat = 1 << 26;
    public char firstUniqChar(String s) {

        char[] arr = s.toCharArray();
        for(char c : arr) {
            updateAppearanceState(c);      
        }
        
        for(int i = 0; i < arr.length; i++) {
            char c = arr[i];
            if(checkHasAppearTwice(c)) {
                return c;
            }       
        }
        return ' ';
    }
    
    // 更新当前的出现状态
    private void updateAppearanceState(char c) {
        if (isUpper(c)) {
            int index = c - 'A';
            if((upperfirstAppear & (1 << index)) != 0)  {
                upperRepeat |= 1 << index;
            } else {
                upperfirstAppear |= 1 << index;
            }
        } else {
            int index = c - 'A';
            if((firstAppear & (1 << index)) != 0)  {
                repeat |= 1 << index;
            } else {
                firstAppear |= 1 << index;
            }
        }
    }    

    
    private boolean checkHasAppearTwice(char c) {
        if(isUpper(c)) {
            int index = c - 'A';
            return (upperfirstAppear & (1 << index)) != 0 && (upperRepeat & (1 << index)) == 0;
        }else {
            int index = c - 'a';
            return (firstAppear & (1 << index)) != 0 && (repeat & (1 << index)) == 0;
        }
    }
    
    
    private boolean isUpper(char c) {
        if(c <= 'z' && c >= 'a') {
            // System.out.println(c - 'A');
            return false;
        }
        return true;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值