day20-字符统计

原来已经十几天没有更新了,真是一时拖延一时爽,一直拖延一直爽

387字符串中的第一个唯一字符

在这里插入图片描述
第一反应就是构建哈希表,一次遍历构建map,另一次遍历找出次数为1的返回
时间复杂度是O(N),空间复杂度是可能出现的字符种类个数,在这里就是26

class Solution {
public:
    int firstUniqChar(string s) {
        unordered_map<int,int> count;
        for(int i = 0; i < s.length(); i++){
            count[s[i]] ++;
        }
        for(int i = 0; i < s.length(); i++){
            if(count[s[i]] == 1) return i;
        }
        return -1;

    }
};

在这里插入图片描述
看了题解说直接用数组计数会快很多,应该是建立哈希表比较复杂

class Solution {
public:
    int firstUniqChar(string s) {
        vector<int> count(27);
        for(int i = 0; i < s.length(); i++){
            count[s[i] - 'a'] ++;
        }
        for(int i = 0; i < s.length(); i++){
            if(count[s[i] - 'a'] == 1) return i;
        }
        return -1;

    }
};

在这里插入图片描述

389找不同

在这里插入图片描述
第一想法还是和上面一样,构建哈希数组进行计数
时间复杂度O(N),空间复杂度也和上面的一样

class Solution {
public:
    char findTheDifference(string s, string t) {
        vector<int> count(27);
        char res;
        for(int i = 0; i < t.length(); i++){
            count[t[i] - 'a'] ++;
        }
        for(int i = 0; i < s.length(); i++){
            count[s[i] - 'a'] --;
        }
        for(int i = 0; i < t.length(); i++){
            if(count[t[i] - 'a'] == 1) res = t[i];
        }
        return res;
        
    }
};

在这里插入图片描述
看了题解之后不得不感慨大家太强了,不需要用哈希表,直接把两个字符串的字符的ascll码相加,两个对应减一下就可以了!这样空间复杂度为O(1)

class Solution {
public:
    char findTheDifference(string s, string t) {
        int sumt = 0;
        int sums = 0;

        for(int i = 0; i < t.length(); i++){
            sumt += t[i];
        }
        for(int i = 0; i < s.length(); i++){
            sums += s[i];
        }
       
        return sumt - sums;
        
    }
};

在这里插入图片描述
还有一种位运算,把两个字符串中的所有字符全部进行异或运算,出现偶数次的那个字符就是要求的,异或运算完的结果就是答案

class Solution {
public:
    char findTheDifference(string s, string t) {
        int res = 0;
        for(char c : t){
            res ^= c;
        }
        for(char c : s){
            res ^= c;
        }
        return res;     
    }
};

在这里插入图片描述

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值