摘要:題目要求假設(shè)兩個(gè)只包含小寫字母的字符串和,其中是中字母的亂序,并在某個(gè)位置上添加了一個(gè)新的字母。最后只需要遍歷整數(shù)數(shù)組檢查是否有某個(gè)字符計(jì)數(shù)大于。
題目要求
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: e Explanation: "e" is the letter that was added.
假設(shè)兩個(gè)只包含小寫字母的字符串s和t,其中t是s中字母的亂序,并在某個(gè)位置上添加了一個(gè)新的字母。問添加的這個(gè)新的字母是什么?
思路一:字符數(shù)組我們可以利用一個(gè)整數(shù)數(shù)組來記錄所有字符出現(xiàn)的次數(shù),在s中出現(xiàn)一次相應(yīng)計(jì)數(shù)加一,在t中出現(xiàn)一次則減一。最后只需要遍歷整數(shù)數(shù)組檢查是否有某個(gè)字符計(jì)數(shù)大于0。則該字符就是多余的字符。
public char findTheDifference(String s, String t) { int[] count = new int[26]; for(int i = 0 ; i思路二:求和 我們知道,字符對(duì)應(yīng)的ascii碼是唯一的,那么既然兩個(gè)字符串相比只有一個(gè)多余的字符,那么二者的ascii碼和相減就可以找到唯一的字符的ascii碼。
public char findTheDifference2(String s, String t){ int value = 0; for(int i = 0 ; i
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.cn/yun/77450.html
摘要:題目鏈接題目分析給定兩個(gè)字符串,其中一個(gè)字符串比另一個(gè)字符串在隨機(jī)位置多一個(gè)字符。思路用計(jì)算字符串中字符出現(xiàn)的次數(shù),對(duì)比兩個(gè)字符串的字符出現(xiàn)次數(shù)。計(jì)算差集,返回差異部分即可。最終代碼若覺得本文章對(duì)你有用,歡迎用愛發(fā)電資助。 D73 389. Find the Difference 題目鏈接 389. Find the Difference 題目分析 給定兩個(gè)字符串,其中一個(gè)字符串比另一...
Problem Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute dif...
摘要:代碼集合法復(fù)雜度時(shí)間空間思路同樣使用集合,但這次我們要維護(hù)集合的大小不超過,相當(dāng)于是記錄一個(gè)寬度為的窗口中出現(xiàn)過的數(shù)字。 Contains Duplicate I Given an array of integers, find if the array contains any duplicates. Your function should return true if any v...
Problem Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at ...
摘要:題目要求扭動(dòng)序列是指數(shù)組中的相鄰兩個(gè)元素的差保證嚴(yán)格的正負(fù)交替,如數(shù)組中相鄰兩個(gè)元素的差為,滿足扭動(dòng)序列的要求?,F(xiàn)在要求從一個(gè)數(shù)組中,找到長度最長的扭動(dòng)子序列,并返回其長度。即前一個(gè)元素和當(dāng)前元素構(gòu)成下降序列,因此代碼如下 題目要求 A sequence of numbers is called a wiggle sequence if the differences between ...
閱讀 1041·2023-04-26 02:26
閱讀 2151·2021-09-26 10:16
閱讀 1557·2019-08-30 12:57
閱讀 3471·2019-08-29 16:10
閱讀 3225·2019-08-29 13:47
閱讀 1191·2019-08-29 13:12
閱讀 2143·2019-08-29 11:11
閱讀 1341·2019-08-26 13:28