zoukankan      html  css  js  c++  java
  • 389. Find the Difference 找出两个字符串中多余的一个字符

    [抄题]:

    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.

     [暴力解法]:

    时间分析:

    空间分析:

     [优化后]:

    时间分析:

    空间分析:

    [奇葩输出条件]:

    [奇葩corner case]:

    [思维问题]:

    [一句话思路]:

    用26数组,先加后减

    [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

    [画图]:

    [一刷]:

    [二刷]:

    [三刷]:

    [四刷]:

    [五刷]:

      [五分钟肉眼debug的结果]:

    [总结]:

    有两种方法取出字母:.toCharArray(无参) 字符串.charAt()。

    异或是个好东西。

    [复杂度]:Time complexity: O(n) Space complexity: O(n)

    [英文数据结构或算法,为什么不用别的数据结构或算法]:

    [关键模板化代码]:

    //for loop, +t, -s 
            for (int i = 0; i < t.length(); i++) {
                alpha[t.charAt(i) - 'a']++;
            }

    [其他解法]:

    异或运算符是用符号“^”表示的,其运算规律是:
    两个操作数的位中,相同则结果为0,不同则结果为1。

    [Follow Up]:

    [LC给出的题目变变变]:

     [代码风格] :

    class Solution {
        public char findTheDifference(String s, String t) {
            //ini char[]
            int[] alpha = new int[26];
            
            //for loop, +t, -s 
            for (int i = 0; i < t.length(); i++) {
                alpha[t.charAt(i) - 'a']++;
            }
            
            for (int i = 0; i < s.length(); i++) {
                alpha[s.charAt(i) - 'a']--;
            }
            
            //return res
            for (int j = 0; j < 26; j++) {
                if (alpha[t.charAt(j) - 'a'] != 0) {
                    return t.charAt(j);
                }
            }
            
            return 0;
        }
    }
    View Code
  • 相关阅读:
    Vue学习笔记(4)-带参数路由,嵌套路由,编程式导航
    JS数组&&数组对象去重
    Vue学习笔记(3)-品牌管理系统
    Vue学习笔记(2)-组件生命周期
    负margin
    CSS布局奇淫巧计之-强大的负边距
    由浅入深漫谈margin属性
    双飞翼布局和圣杯布局的对比
    圣杯布局的实现过程
    CSS实现垂直居中的5种方法
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8931287.html
Copyright © 2011-2022 走看看