找不同

找不同

题目

给定两个字符串 s 和 t,它们只包含小写字母。
字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。
请找出在 t 中被添加的字母。
示例 1:
输入:s = "abcd", t = "abcde"
输出:"e"
解释:'e' 是那个被添加的字母。
示例 2:
输入:s = "", t = "y"
输出:"y"
示例 3:
输入:s = "a", t = "aa"
输出:"a"
示例 4:
输入:s = "ae", t = "aea"
输出:"a"
提示:
0 <= s.length <= 1000
t.length == s.length + 1
s 和 t 只包含小写字母

1.土方法:利用ASCII码值计算t和s的差值,

思路:

s="abcd" 的ASCII值和=394(即'a'+'b'+'c'+'d'=97+98+99+100=394)
t="abcde"(或打乱顺序"edcba") 的ASCII值和=495
(t-s)=495-394=101 (101 对应'e')

土方法代码A

package com.litetlewhite.practice;

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String s = scanner.nextLine();
        String t = scanner.nextLine();
        int dValue = 0;   //存放 s 和 t 的ASCII码差值

        for (int i = 0; i < t.length(); i++)
            dValue = dValue + t.charAt(i);  //假设t="edcba" 则循环结束后 dValue=495
        for (int i = 0; i < s.length(); i++)
            dValue = dValue - s.charAt(i);  //假设s="abcd" 则循环结束后 dValue=495-394=101

        System.out.println((char) (dValue));
        scanner.close();
    }
}

土方法代码B

#include <iostream>

using namespace std;

int main(){
    int sA = 0; //存放 s 串的ASCII值的和
    int tA = 0; //存放 t 串的ASCII值的和
    char temp;

    for (int i = 0; i < 1000; i++){
        temp = getchar();
        if (temp == ' ' || temp == '\n') break; //遇到空格或回车停止输入
        else sA = sA + temp;
    }

    for (int i = 0; i < 1000; i++){
        temp = getchar();
        if (temp == ' ' || temp == '\n') break;
        else tA = tA + temp;
    }

    cout << (char)(tA - sA);

    return 0;
}

土方法运行结果

image



2.直接比较法:

字符串s和t
因为字符串t是再s的基础上打乱顺序,在随机位置添加一个新的字母
所以t里的某个字符需要到s里遍历寻找
再从t里取每个字符t[i]去跟s[0]、s[1]、s[2]比较
如:s=abcd t=deacb(打乱顺序,添加字母e)
  t里的第一的字母d 在s里遍历寻找,找到则不是不同字母
  e在 s里未能找到,所以e是不同

代码:

#include<iostream>

using namespace std;

int main() {
    string s, t;
    int haveSame;
    cin >> s >> t;
    for (int i = 0; i < t.length(); i++) {
        haveSame=0;
        for (int j = 0; j < s.length(); j++)
            if (t[i] == s[j]) {
                haveSame = 1;
                break;
            }
        if (!haveSame) {
            cout << t[i];
            break;
        }
    }
    return 0;
}

比较法运行结果:未能实现

image

因为该方法思路是:在字符串s中寻找出现过的字母
如 s="a"、t="aa",则t的第二个a在s中被找到了,即a在s里出现过了,所以不会把第二个a当作新添字母

posted @ 2021-07-16 13:35  为搞钱而写代码  阅读(81)  评论(0)    收藏  举报