第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<String, Integer> 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<String, Long> hash = Arrays.stream(input.split(""))
			.collect(
				Collectors.groupingBy(Function.identity(), Collectors.counting())
			);
		hash.forEach((key, value) -> System.out.println(key + " : " + value));
	}
}

运行截图

第二题

题目简述

编写程序,输入一个字符串,判断该串中的字母能否组成一个回文串(回文串:一个字符串从前向后读取和从后向前读取都一样)。如:abc?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()));
	}
}

运行截图


原文地址:https://www.cnblogs.com/jinma/p/11889190.html