【leetcode】389. Find the Difference

原创 2016年08月31日 16:49:59

一、题目描述

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;
    }
};





版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

LeetCode笔记:389. Find the Difference

在两个字符串中找出唯一多出的那个字母

LeetCode 389. Find the Difference

题意两个字符串s,t,都是小写字母,t由s中的字符和新增的一个字母随机排列组合而成,找出新增的字符!思路最直接的思路是HashMap,根据字符串s建立一个HashMap,key是字母,value是字母...

leetcode389. Find the Difference

389. Find the DifferenceGiven two strings s and t which consist of only lowercase letters.String t i...

leetcode算法——389. Find the Difference(基于JAVA)

Given two strings s and t which consist of only lowercase letters. String t is generated by random s...

【LeetCode】389 Find the Difference(java)

原题Given two strings s and t which consist of only lowercase letters.String t is generated by random ...

[LeetCode]389. Find the Difference(找不同)

389. Find the DifferenceGiven two strings s and t which consist of only lowercase letters. String t...

[LeetCode]242.Valid Anagram&383. Ransom Note&389. Find the Difference

242.Valid Anagram 383. Ransom Note 389. Find the Difference

【Leetcode】389. Find the Difference

方法一: 思路: 利用一个HashMap,先统计s字符串中每个字符出现的次数,然后遍历t字符串,若该字符未包含在HashMap中或出现次数等于0,立即返回该字符,否则,该字符出现的次数减一。 pub...

389. Find the Difference

原题链接: https://leetcode.com/problems/find-the-difference/ 题目: Given two strings s and t which cons...

389. Find the Difference [easy] (Python)

题目链接https://leetcode.com/problems/find-the-difference/题目原文 Given two strings s and t which consist...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)