第11次作业--字符串处理

第一题

题目简述

编写一个应用程序,统计输入的一个字符串中相同字符的个数,并将统计结果输出。

解决方案-1

package homework.eleven;

import java.util.*;

public class One {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        final String input = scanner.nextLine();

        Map hash = new HashMap<>(input.length());
        Arrays.stream(input.split("")).forEach(e -> hash.compute(e, (k, v) -> v == null ? 1 : v + 1));

        hash.forEach((key, value) -> System.out.println(key + " : " + value));
    }
}

解决方案-2

package homework.eleven;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

public class One {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        final String input = scanner.nextLine();

        Map hash = Arrays.stream(input.split(""))
            .collect(
                Collectors.groupingBy(Function.identity(), Collectors.counting())
            );
        hash.forEach((key, value) -> System.out.println(key + " : " + value));
    }
}

运行截图

第11次作业--字符串处理_第1张图片

第二题

题目简述

编写程序,输入一个字符串,判断该串中的字母能否组成一个回文串(回文串:一个字符串从前向后读取和从后向前读取都一样)。如:ab c?ba

源代码

package homework.eleven;

import java.util.Scanner;

public class Two {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        final String input = scanner.nextLine();
        StringBuilder sb = new StringBuilder(input);
        System.out.println(input.equals(sb.reverse().toString()));
    }
}

运行截图

第11次作业--字符串处理_第2张图片
第11次作业--字符串处理_第3张图片

你可能感兴趣的:(第11次作业--字符串处理)