日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

LeetCode之Find the Difference

發布時間:2023/12/4 编程问答 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 LeetCode之Find the Difference 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

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]);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、總結

看到2個字符串對比,我么可以先轉化為字符數組,下表從A - 65 活著 ?a - 95 ?開始,也就是從下表0開始,然后要注意2個字符串里面可能包含同樣的元素有幾個的情況,相同就往上加,另外一個就減,但是他們最多相差1個字符,所以,我們可可以肯定,比我們一開始設置的大,也就是3,然后如果沒有重復的數據,那么一樣的就為1,肯定有一個為2.

總結

以上是生活随笔為你收集整理的LeetCode之Find the Difference的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。