LeetCode之Find the Difference
生活随笔
收集整理的這篇文章主要介紹了
LeetCode之Find the Difference
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
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、代碼實(shí)現(xiàn)
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]);elsea[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]);elsea[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、總結(jié)
看到2個(gè)字符串對(duì)比,我么可以先轉(zhuǎn)化為字符數(shù)組,下表從A - 65 活著 ?a - 95 ?開(kāi)始,也就是從下表0開(kāi)始,然后要注意2個(gè)字符串里面可能包含同樣的元素有幾個(gè)的情況,相同就往上加,另外一個(gè)就減,但是他們最多相差1個(gè)字符,所以,我們可可以肯定,比我們一開(kāi)始設(shè)置的大,也就是3,然后如果沒(méi)有重復(fù)的數(shù)據(jù),那么一樣的就為1,肯定有一個(gè)為2.
總結(jié)
以上是生活随笔為你收集整理的LeetCode之Find the Difference的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: LeetCode之Single Numb
- 下一篇: LeetCode之Missing Num