Find the Difference

来源:互联网 发布:青岛少儿编程培训班 编辑:程序博客网 时间:2024/05/18 05:38

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:eExplanation:'e' is the letter that was added.
思路:注意一点就是:最后return的时候,计算char的index位移,需要转换成char。

public class Solution {    public char findTheDifference(String s, String t) {        int[] chars = new int[26];        for(int i=0; i<t.length(); i++){            char c = t.charAt(i);            chars[c-'a']++;        }                for(int i=0; i<s.length(); i++){            char c = s.charAt(i);            chars[c-'a']--;        }                for(int i=0; i<chars.length; i++){            if(chars[i] != 0 ){                return (char)('a'+i);            }        }        return t.charAt(0);    }}






0 0
原创粉丝点击