【leetcode】389. Find the Difference

找出字符串中新增的字母
本文介绍了一种算法,用于从两个字符串中找出一个字符串相对于另一个字符串新增加的字母。通过两种方法实现:一种是利用哈希表统计字符频率;另一种是通过异或操作简化计算过程。

一、题目描述

Given two strings s and t which consist of only lowercase letters.

String t is generated by random shuffling string s and then add one more letter at a random position.

Find the letter that was added in t.

Example:

Input:
s = "abcd"
t = "abcde"

Output:
e

Explanation:
'e' is the letter that was added.

思路:因为t 为s 的一个子字符串,因此t 可能比s 长,也可能比s 短,先判断s 和t 的长短,将长的字符串赋值给str1, 短的字符串赋值给str2。然后用一个map,遍历长的字符串并存储每个字符出现的次数,再遍历一遍短的字符串,对每个字符出现一次便减掉一次。最后遍历map,值为1 对应的字符即是多出来的字符。


c++代码(22ms)

class Solution {
public:
    char findTheDifference(string s, string t) {
        int len1=s.length();
    	int len2=t.length();
    	string str1,str2;  //str1存长的字符串 
    	if(len1>len2){
    		str1 = s;
    		str2 = t;
    	}else{
    		str1 = t;
    		str2 = s;
    	}//if
    	
    	map<char, int> a;
    	for(int i=0; i<s.length(); i++){
    		a[s[i]]++;
    	}//for
    	for(int i=0; i<t.length(); i++){
    		a[t[i]]--;
    	}
    	map<char, int>::iterator it;
    	for(it=a.begin(); it!=a.end(); it++){
    		if(it->second){
    			return (it->first);
    		}
    	}//for
    	return 'c';
    }
};


方法二:使用异或,因为A ^ B ^ A = B

c++代码(4ms)

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





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值