码迷,mamicode.com
首页 > 其他好文 > 详细

*389. Find the Difference (string + map(26)) read problems carefully

时间:2018-06-09 00:09:17      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:har   turn   ons   art   TE   ring   XA   find   length   

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.

 

class Solution {
    public char findTheDifference(String s, String t) {
        //in the middle(start) or  in the end
        //get small length
        int sn = s.length();
        int tn = t.length();
        if(sn > tn)
        return helper(s,t);
        else return helper(t,s);
    }
    char helper(String l, String s){ // larger and smaller
        int[] a = new int[26];
        int[] b = new int[26];
        for(int i = 0; i<l.length(); i++){
            a[l.charAt(i) - ‘a‘] ++;
        }
        for(int i = 0; i<s.length(); i++){
            b[s.charAt(i) - ‘a‘] ++;
        }
        for(int i = 0; i<26; i++){
            if(a[i] != b[i]) return (char)(i+‘a‘);
        }
        return ‘a‘;
    }
}

 

*389. Find the Difference (string + map(26)) read problems carefully

标签:har   turn   ons   art   TE   ring   XA   find   length   

原文地址:https://www.cnblogs.com/stiles/p/leetcode389.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!