【leetcode】找不同c++

题目描述:
给定两个字符串 s 和 t,它们只包含小写字母。

字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。

请找出在 t 中被添加的字母。

示例1:

输入:s = “abcd”, t = “abcde”
输出:“e”
解释:‘e’ 是那个被添加的字母。

示例2:

输入:s = “”, t = “y”
输出:“y”

示例3:

输入:s = “a”, t = “aa”
输出:“a”

示例4:

输入:s = “ae”, t = “aea”
输出:“a”

提示:

  • 0 <= s.length <= 1000
  • t.length == s.length + 1
  • s 和 t 只包含小写字母

代码:

class Solution {
    
    
public:
    char findTheDifference(string s, string t) {
    
    
        int nums[26]; //记录26个字母每个字母在s中出现的次数
        for(int i=0;i<26;i++){
    
    
            nums[i]=0;
        }
        int n1=s.length(),n2=t.length();
        for(int i=0;i<n1;i++){
    
    //记录在s中出现的次数
            nums[s[i]-'a']++; 
        }
        for(int i=0;i<n2;i++){
    
     //在t中查找匹配
            if(nums[t[i]-'a']==0){
    
      //若该字母在s中出现的次数为0,直接返回该字母
                return t[i];
            }
            if(nums[t[i]-'a']!=0){
    
     //若该字母在s中出现次数不为0,将t中的字母用于匹配,然后次数减去1
                nums[t[i]-'a']--;
            }
        }
        return '0';
    }
};

数组下标法

注意s和t中都可能出现重复字母,不能用默认key去重的map存储字符串s中的字母和字母出现的次数。

因为题目限定字符串中只可能出现小写字母,使用字符数组nums[26]保存即可,下标为s[i]-‘a’~[0,25]。

先遍历s,记录每个字母出现的次数,再在t中依次检查是否匹配,若匹配则总次数-1,若次数为0说明该字母在s和t中不重复,返回该果字符。

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_40315080/article/details/120650391