CF——1721A - Image

Image

  • 题目
  • 思路
  • 代码
  • 结果

题目

You have an image file of size 2×2, consisting of 4 pixels. Each pixel can have one of 26 different colors, denoted by lowercase Latin letters.

You want to recolor some of the pixels of the image so that all 4 pixels have the same color. In one move, you can choose no more than two pixels of the same color and paint them into some other color (if you choose two pixels, both should be painted into the same color).

What is the minimum number of moves you have to make in order to fulfill your goal?

Input
The first line contains one integer t (1≤t≤1000) — the number of test cases.

Each test case consists of two lines. Each of these lines contains two lowercase letters of Latin alphabet without any separators, denoting a row of pixels in the image.

Output
For each test case, print one integer — the minimum number of moves you have to make so that all 4 pixels of the image have the same color.
题目传送门
大致意思,每一组测试用例有两行四个字母,你需要将这些四个字母变得一模一样,每次可以选择不超过两个相同字母将他们变为相同的颜色。比如你可以将a变成c,如果要选择两个字母的话,那么就得两个子母都一样,比如将cc变成bb。

思路

其实就是个打表题,如果四个字母不一样,那么就需要三次,将其中三个字母变成第四个字母。如果四个字母有三种,那么就只需要将两个相同的字母变为另外一个字母,这计数一次,然后,再选择最后的那个不同的子母变为相同即可。如果字母有两种,无论是一比三还是二比二,都只需要一次就可以相同。四个字母相同那就不用变了。
打表

代码

import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class Main {
    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        int num = reader.nextInt();//接收测试用例个数
        for (int i = 0; i < num; ++i) {
            String a = reader.next();
            String b = reader.next();
            Set<Character> set = new HashSet<>();
            set.add(a.charAt(0));
            set.add(a.charAt(1));
            set.add(b.charAt(0));
            set.add(b.charAt(1));
            if (set.size() == 4)
                System.out.println(3);
            else if (set.size() == 3)
                System.out.println(2);
            else if (set.size() == 2)
                System.out.println(1);
            else
                System.out.println(0);
        }

    }
}

结果

AC

你可能感兴趣的:(模拟题,LeetCode,java,开发语言)