前言
牛客是需要处理输入和输出的,输入要注意审题看是不是有多组输入,输入的字符串处理一般用scanner就可以搞定了。输出注意格式包括空格和回车换换。
力扣只需要关心核心代码。而且牛客考试题目是 相当于给 一个写字板啥都没,然后编码,这个要 提前练习。
BigDecimal
涉及到数字超了、精度、四舍五入等
// 第二个参数scale为1,表示保留1位小数
// 第三个参数表示四舍五入
BigDecimal zsAvg = bd.divide(BigDecimal.valueOf(size), 1, RoundingMode.HALF_UP);
/**
* Returns a {@code BigDecimal} whose value is {@code (this /
* divisor)}, and whose scale is as specified. If rounding must
* be performed to generate a result with the specified scale, the
* specified rounding mode is applied.
*
* @param divisor value by which this {@code BigDecimal} is to be divided.
* @param scale scale of the {@code BigDecimal} quotient to be returned.
* @param roundingMode rounding mode to apply.
* @return {@code this / divisor}
* @throws ArithmeticException if {@code divisor} is zero,
* {@code roundingMode==RoundingMode.UNNECESSARY} and
* the specified scale is insufficient to represent the result
* of the division exactly.
* @since 1.5
*/
public BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode) {
return divide(divisor, scale, roundingMode.oldMode);
}
问:怎么去判断什么时候需要用BigInteger和BigDecimal
Scanner
常见输入,测试时可以用字符串,跑代码时用标准输入流
// 构造函数可以为字符串
Scanner scanner = new Scanner("abcdfe");
// 构造函数可以标准输入流
Scanner scanner = new Scanner(System.in);
Scanner处理有开头和结尾的数组
import java.util.Scanner;
public class LearnInput {
public static void main(String args[]) {
Scanner scanner = new Scanner("[1,2,3,4,5]");
scanner.useDelimiter("[\\[\\],]");
while (scanner.hasNextInt()) {
System.out.println(scanner.nextInt());
}
}
}
输出结果
// 输出
1
2
3
4
5
scanner可以一次读取一行也可以一次都去一个数字
字符串求所有子串
例子:求美丽值,涉及到求一个字符串的所有子串
package leetcode;
import java.util.*;
/**
* https://leetcode-cn.com/problems/sum-of-beauty-of-all-substrings/
* 1781. 所有子字符串美丽值之和
* */
public class C1781 {
public static void main(String args[]) {
Solution solution = new Solution();
Scanner scanner = new Scanner("xzvfsppsjfbxdwkqe");
String str = scanner.nextLine();
System.out.println(str);
System.out.println(solution.beautySum(str));
}
static class Solution {
int[] freq = new int[26];
public int beautySum(String s) {
List<String> subStrings = allSubString(s);
int sum = 0;
for (String ss:subStrings) {
sum += beauty(ss);
}
return sum;
}
private List<String> allSubString(String s) {
List<String> all = new ArrayList<>();
for ( int i = 0; i < s.length(); ++i ) {
for ( int j = i+1; j <= s.length(); ++j ){
String tmp = s.substring(i,j);
if (tmp.length()<=2) {
continue;
}
all.add(tmp);
}
}
return all;
}
/**
* 求出单个字符串的美丽值
*/
private int beauty(String s) {
Arrays.fill(freq, 0);
for (int i=0;i<s.length(); ++i) {
int index = s.charAt(i) - 'a';
freq[index] = freq[index] + 1;
}
int min = Integer.MAX_VALUE;
int max = 0;
for (int i : freq) {
if (0 == i) {
continue;
}
min = Math.min(min, i);
max = Math.max(max, i);
}
return max-min;
}
}
}