资讯专栏INFORMATION COLUMN

leetcode389.Find The Difference

cyqian / 2573人阅读

摘要:题目要求假设两个只包含小写字母的字符串和,其中是中字母的乱序,并在某个位置上添加了一个新的字母。最后只需要遍历整数数组检查是否有某个字符计数大于。

题目要求
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.

假设两个只包含小写字母的字符串s和t,其中t是s中字母的乱序,并在某个位置上添加了一个新的字母。问添加的这个新的字母是什么?

思路一:字符数组

我们可以利用一个整数数组来记录所有字符出现的次数,在s中出现一次相应计数加一,在t中出现一次则减一。最后只需要遍历整数数组检查是否有某个字符计数大于0。则该字符就是多余的字符。

    public char findTheDifference(String s, String t) {
        int[] count = new int[26];
        for(int i = 0 ; i
思路二:求和

我们知道,字符对应的ascii码是唯一的,那么既然两个字符串相比只有一个多余的字符,那么二者的ascii码和相减就可以找到唯一的字符的ascii码。

    public char findTheDifference2(String s, String t){
        int value = 0;
        for(int i = 0 ; i           
               
                                           
                       
                 

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/77450.html

相关文章

  • Leetcode PHP题解--D73 389. Find the Difference

    摘要:题目链接题目分析给定两个字符串,其中一个字符串比另一个字符串在随机位置多一个字符。思路用计算字符串中字符出现的次数,对比两个字符串的字符出现次数。计算差集,返回差异部分即可。最终代码若觉得本文章对你有用,欢迎用爱发电资助。 D73 389. Find the Difference 题目链接 389. Find the Difference 题目分析 给定两个字符串,其中一个字符串比另一...

    widuu 评论0 收藏0
  • [LintCode/LeetCode] Contains Duplicate III

    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...

    MageekChiu 评论0 收藏0
  • [Leetcode] Contains Duplicate 包含重复

    摘要:代码集合法复杂度时间空间思路同样使用集合,但这次我们要维护集合的大小不超过,相当于是记录一个宽度为的窗口中出现过的数字。 Contains Duplicate I Given an array of integers, find if the array contains any duplicates. Your function should return true if any v...

    rozbo 评论0 收藏0
  • [LintCode/LeetCode] Contains Duplicate II

    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 ...

    894974231 评论0 收藏0
  • leetcode376. Wiggle Subsequence

    摘要:题目要求扭动序列是指数组中的相邻两个元素的差保证严格的正负交替,如数组中相邻两个元素的差为,满足扭动序列的要求。现在要求从一个数组中,找到长度最长的扭动子序列,并返回其长度。即前一个元素和当前元素构成下降序列,因此代码如下 题目要求 A sequence of numbers is called a wiggle sequence if the differences between ...

    CoffeX 评论0 收藏0

发表评论

0条评论

cyqian

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<