首页 > 学院 > 开发设计 > 正文

【Leetcode】389. Find the Difference

2019-11-06 07:51:14
字体:
来源:转载
供稿:网友

方法一:

思路:

利用一个HashMap,先统计s字符串中每个字符出现的次数,然后遍历t字符串,若该字符未包含在HashMap中或出现次数等于0,立即返回该字符,否则,该字符出现的次数减一。

public class Solution {    public char findTheDifference(String s, String t) {        Map<Character, Integer> map = new HashMap<Character, Integer>();        int sLen = s.length();        int tLen = t.length();        int j = 0;        char result = 0;	   	for (int i = 0; i < sLen; i++) { 	   	    char s0 = s.charAt(i);	   		if (map.containsKey(s0))	   			map.put(s0, map.get(s0) + 1); 	   		else	   			map.put(s0, 1);	   	}	   	for (int i = 0; i < tLen; i++) { 	   	    char t0 = t.charAt(i);	   		if (map.containsKey(t0)) {	   			if (map.get(t0) == 0) {	   				result = t0;					break;				}	   			map.put(t0, map.get(t0) - 1);	   		}	   		else {	   			result = t0;				break;			}		}	   	return result;    }}

Runtime:27ms

方法二:

思路:

利用一个数组,先统计s字符串中每个字符出现的次数,然后遍历t字符串,若该字符的出现次数等于0,立即返回该字符,否则,该字符出现的次数减一。

public class Solution {    public char findTheDifference(String s, String t) {        int sLen = s.length();        int tLen = t.length();        int hash[] = new int[26];  	    char result = 0;	    for (int i = 0; i < sLen; i++)  	        hash[s.charAt(i) - 'a']++;     	   	for (int i = 0; i < tLen; i++) { 	   		if (hash[t.charAt(i) - 'a'] == 0) {	   			result = t.charAt(i);				break;	   		}	   		else 	   			hash[t.charAt(i) - 'a']--;  		}	   	return result;    }}

Runtime:8ms


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表