LeetCode389-找不同(查找)

查找问题,最先想到Map和Set

一开始觉得用set即可,因为把s的内容存进去,对t进行遍历,不在里面的肯定就是新增加的了

    public char findTheDifference(String s, String t) {
        Set<Character> set = new HashSet<>();

        int lenS = s.length();
        int lenT = t.length();

        for(int i=0;i<lenS;i++){
            set.add(s.charAt(i));
        }

        char result = ' ';

        for (int i=0;i<lenT;i++){
            if(!set.contains(t.charAt(i))){
                result = t.charAt(i);
                break;
            }
        }

        return result;
    }

但是没有考虑到,相同字母的问题

用HashMap,把每个字母存进去,然后存对应的值。

1、如果t中的某个字母不在Map中,他就是多出来的。

2、如果t中的字母,在Map中,但是个数不一样,他就是多出来的。

用Map麻烦,因为是24个字母,用数组即可

首先确认两件事情

a的数值是97,int数组默认是0

char c = 'a';
        System.out.println((int)c);//97

        int [] ss = new int[24];
        System.out.println(ss[1]);//0

26个字母,记成24了。。。

public char findTheDifference(String s, String t) {
        int [] ss = new int[26];

        int lenS = s.length();
        int lenT = t.length();

        //将s的字符对应的位置++
        for(int i=0;i<lenS;i++){
            ss[(int)s.charAt(i)-97]++;
        }

        char result = ' ';

        //如果t中有相应的字符,那就--进行抵消
        //如果数组变成负数了,这个位置的字符就是多出来的
        for(int i=0;i<lenT;i++){

            int temp = --ss[(int)t.charAt(i)-97];
            if(temp==-1){
                result = t.charAt(i);
                break;
            }

        }

        return result;
    }

国内leetcode有问题。。

第一次

然后同样的代码,第二次

原文地址:https://www.cnblogs.com/weizhibin1996/p/9644035.html