首页 > 其他 > 详细

LeetCode Find the Difference

时间:2017-01-01 08:00:02      阅读:175      评论:0      收藏:0      [点我收藏+]

原题链接在这里: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 }

也可以直接采用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 }

类似Single Number.

LeetCode Find the Difference

原文:http://www.cnblogs.com/Dylan-Java-NYC/p/6240686.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!