LeetCode 389. Find the Difference

原题链接在这里:https://leetcode.com/problems/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.

题解:

可用Bit Manipulation, t的每个char ^ s的每个char, 剩下的就是diff.

Time Complexity: O(t.length()). Space: O(1).

AC Java:

 1 public class Solution {
 2     public char findTheDifference(String s, String t) {
 3         char c = t.charAt(t.length()-1);
 4         for(int i = s.length()-1; i>=0; i--){
 5             c ^= s.charAt(i);
 6             c ^= t.charAt(i);
 7         }
 8         return c;
 9     }
10 }

AC C++:

 1 class Solution {
 2 public:
 3     char findTheDifference(string s, string t) {
 4         char res = 0;
 5         for(char c : s){
 6             res ^= c;
 7         }
 8 
 9         for(char c : t){
10             res ^= c;
11         }
12 
13         return res;
14     }
15 };

也可以直接采用char code 得出diff

Time Complexity: O(t.length()). Space: O(1).

AV Java:

 1 public class Solution {
 2     public char findTheDifference(String s, String t) {
 3         int charCodeDiff = 0;
 4         for(int i = 0; i<s.length(); i++){
 5             charCodeDiff -= (int)s.charAt(i);
 6             charCodeDiff += (int)t.charAt(i);
 7         }
 8         charCodeDiff += t.charAt(t.length()-1);
 9         return (char)charCodeDiff;
10     }
11 }

AC C++:

 1 class Solution {
 2 public:
 3     char findTheDifference(string s, string t) {
 4         int n = s.size();
 5         for(int i = 0; i < n; i++){
 6             t[n] += t[i] - s[i]; 
 7         }
 8 
 9         return t[n];
10     }
11 };

类似Single Number.

posted @ 2017-01-01 06:15  Dylan_Java_NYC  阅读(190)  评论(0编辑  收藏  举报