LeetCode之Find the Difference
发布日期:2021-06-29 14:08:03 浏览次数:2 分类:技术文章

本文共 1693 字,大约阅读时间需要 5 分钟。

1、题目

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.
please:
Input:
 
s = "a"
t = "aa"
 
Output:
a
 

2、代码实现

public class Solution {    public static char findTheDifference(String s, String t) {    	if (s == null || t.length() == 0)     		return t.charAt(0);    	if (t == null || t.length() == 0)     		return s.charAt(0);    	if (s == null && t == null)    		return 0;    	int[] a = new int[30];    	char[] tChars = t.toCharArray();    	char[] sChars = s.toCharArray();    	int sLength = s.length();    	int tLength = t.length();    	if (sLength > tLength) {    		for (int i = 0; i < sChars.length; i++) {    			 if (a[sChars[i] - 97] != 0)    				 a[sChars[i] - 97] = ++(a[sChars[i] - 97]);    			 else    				 a[sChars[i] - 97] = 2;    		}    		for (int i = 0; i < tChars.length; i++) {    			a[tChars[i] - 97] = --(a[tChars[i] - 97]);    		    }    	} else {    		for (int i = 0; i < tChars.length; i++) {    			if (a[tChars[i] - 97] != 0)   				 a[tChars[i] - 97] = ++(a[tChars[i] - 97]);   			 else   				 a[tChars[i] - 97] = 2;   		    }    		for (int i = 0; i < sChars.length; i++) {    			a[sChars[i] - 97] = --(a[sChars[i] - 97]);    		    }    	}    	for (int i = 0; i < 30; i ++) {    		if (a[i] >= 2) {    			return (char) (i + 97);    		}     	}    	return 0;    }}
 

3、总结

看到2个字符串对比,我么可以先转化为字符数组,下表从A - 65 活着  a - 95  开始,也就是从下表0开始,然后要注意2个字符串里面可能包含同样的元素有几个的情况,相同就往上加,另外一个就减,但是他们最多相差1个字符,所以,我们可可以肯定,比我们一开始设置的大,也就是3,然后如果没有重复的数据,那么一样的就为1,肯定有一个为2.

转载地址:https://chenyu.blog.csdn.net/article/details/67845937 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:LeetCode之Missing Number
下一篇:LeetCode之First Unique Character in a String

发表评论

最新留言

感谢大佬
[***.8.128.20]2024年04月29日 04时31分49秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章