• 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有问题。。

    第一次

    然后同样的代码,第二次

  • 相关阅读:
    中金所期货(future)指数
    Nginx负载均衡算法之四
    WSGI协议
    Flask 响应之定制全局有效的错误页面,之设置cookie,头信息。
    Python数据结构之栈,队列和堆
    三、Oracle 游标、存储过程、存储函数、触发器
    二、Oracle的结构学习
    一、Oracle的SQL语句学习
    oracle中的修改表结构
    eclipse编写xml文件时类名的自动补全(使用sts插件)
  • 原文地址:https://www.cnblogs.com/weizhibin1996/p/9644035.html
Copyright © 2020-2023  润新知