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
  • 相关阅读:
    .NET 并行编程——数据并行
    .NET Unity XML 配置文件(2)
    Java 判断字符串第一位和最后一位,并截取
    Python的datetime模块分析
    springMVC自定义注解实现用户行为验证
    python hex() oct() bin() math 内置函数
    excel表格 xls、xlsx 读取
    Java中对List集合内的元素进行顺序、倒序、随机排序的示例代码
    node服务器中打开html文件的两种方法
    利用 Express 托管静态文件
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8931287.html
Copyright © 2011-2022 走看看