389. Find the Difference

2018/04/13 leetcode 共 571 字,约 2 分钟

Title

the problem link

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.

题目大意:找多出来的那个字符是啥

Solution

自己做的,AC,这个还可以用SOR异或做的

//cpp:
class Solution {
public:
	char findTheDifference(string s, string t) {
		int nums[256] = { 0 };
		for (int i = 0; i < s.length(); i++) {
			nums[s[i]]++;
		}
		for (int i = 0; i < t.length(); i++) {
			if (nums[t[i]] > 0) {
				nums[t[i]]--;
			}
			else {
				return t[i];
			}
		}
		return -1;
	}
};

Search

    Table of Contents