• 389. Find the Difference


    Given two stringssandtwhich consist of only lowercase letters.

    Stringtis generated by random shuffling stringsand then add one more letter at a random position.

    Find the letter that was added int.

    Example:

    Input:
    s = "abcd"
    t = "abcde"
    
    Output:
    e
    
    Explanation:
    'e' is the letter that was added.
    题目大意是给定两个字符串s和t,t是由s打乱组合而成,并随机插入一个字母。找到这个添加的字母
    可以将字符串的每一个字母放入集合中,求两个集合的差集,可是...这样是不对的,题目又没说添加的字母是否出现过。仍然可以沿用求差的思想,不过是字符ASCII值的差。
    代码如下:
    public class Solution {
        public char findTheDifference(String s, String t) {
            int charCodeS = 0, charCodeT = 0;
            for (int i = 0; i < s.length(); ++i) charCodeS += (int)s.charAt(i);
            for (int i = 0; i < t.length(); ++i) charCodeT += (int)t.charAt(i);
            return (char)(charCodeT - charCodeS);
        }
    }
    分别对两个字符串进行遍历,s和t的长度只差1,可以对上面代码小小的优化,使用一个for循环
    public char findTheDifference(String s, String t) {
            int b=0;
            for(int i = 0; i < t.length();i++) 
            {
                b += (int)t.charAt(i);
                if(i < s.length())
                    b -= (int)s.charAt(i);
            }   
            return (char)b;
        }
     
     
  • 相关阅读:
    CentOS6.4 安装 codeblocks-12.11
    SpringCloud 进阶之Hystrix(断路器)
    SpringCloud 进阶之Ribbon和Feign(负载均衡)
    SpringCloud 进阶之Eureka(服务注册和发现)
    SpringCloud 入门
    SpringBoot与消息(RabbitMQ)
    SpringBoot 与缓存
    SpringBoot 之数据访问
    Spring Data 之 Repository 接口
    Spring Data之Hello World
  • 原文地址:https://www.cnblogs.com/wxshi/p/7598400.html
Copyright © 2020-2023  润新知