leetcode389.Find The Difference

栏目: 编程工具 · 发布时间: 5年前

内容简介:假设两个只包含小写字母的字符串s和t,其中t是s中字母的乱序,并在某个位置上添加了一个新的字母。问添加的这个新的字母是什么?我们可以利用一个整数数组来记录所有字符出现的次数,在s中出现一次相应计数加一,在t中出现一次则减一。最后只需要遍历整数数组检查是否有某个字符计数大于0。则该字符就是多余的字符。我们知道,字符对应的ascii码是唯一的,那么既然两个字符串相比只有一个多余的字符,那么二者的ascii码和相减就可以找到唯一的字符的ascii码。

题目要求

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<t.length() ; i++) {
            if(i != t.length()-1) {
                count[s.charAt(i)-'a']++;
            }
            count[t.charAt(i)-'a']--;
        }
        for(int i = 0 ; i<count.length ; i++) {
            if(count[i] != 0) {
                return (char)('a' + i);
            }
        }
        return 'a';
    }

思路二:求和

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

public char findTheDifference2(String s, String t){
        int value = 0;
        for(int i = 0 ; i<s.length() ; i++) {
            value -= s.charAt(i);
            value += t.charAt(i);
        }
        char result = (char)(value + t.charAt(t.length()-1)); 
        return result;
    }

以上所述就是小编给大家介绍的《leetcode389.Find The Difference》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Beginning ASP.NET 4 in C# and Vb

Beginning ASP.NET 4 in C# and Vb

Imar Spaanjaars / Wrox / 2010-3-19 / GBP 29.99

This book is for anyone who wants to learn how to build rich and interactive web sites that run on the Microsoft platform. With the knowledge you gain from this book, you create a great foundation to ......一起来看看 《Beginning ASP.NET 4 in C# and Vb》 这本书的介绍吧!

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器