目录
学习内容:
LintCode刷题:
·比较字符串
首先创建一个全部都是0的数组,长度到128,再将A字符串遍历,所有字符所在位置都将数字++,然后遍历B字符串,所有字符所在位置都将数字--,当这个数组中有<0的部分就返回false,其余返回ture即可
public class Solution {
public boolean compareStrings(String A, String B) {
int[] countsByChar = new int[128];
for (char c : A.toCharArray()) {
countsByChar[c]++;
}
for (char c : B.toCharArray()) {
countsByChar[c]--;
if (countsByChar[c] < 0) return false;
}
return true;
}
}
·创建ArrayList集合并添加数据
创建String类型的ArrayList然后添加数据并返回
import java.util.ArrayList;
public class Solution {
public ArrayList<String> createList(String str1, String str2) {
ArrayList<String> arrayList=new ArrayList<String>();
arrayList.add(str1);
arrayList.add(str2);
return arrayList;
}
}
· 打印春夏秋冬的特点
使用枚举,创建以及方法使用
public enum Season {
SPRING("spring","spring returns and everything comes back to life"),
SUMMER("Summmer", "the summer heat is sweetest with you"),
AUTUMN("Autumn", "autumn winds and floodwaters rise"),
WINTER("Winter", "the north wind is howling and the snow is drifting");
private String name;
private String feature;
Season(String name, String feature) {
this.name = name;
this.feature = feature;
}
public String getName() {
return name;
}
public String getFeature() {
return feature;
}
@Override
public String toString() {
return name + ": " + feature + ".";
}
}
public class Main {
Season spring;
public Main(Season spring) {
this.spring=spring;
}
public static void main(String[] args) {
Main
SPRING=new Main(Season.SPRING),
SUMMER=new Main(Season.SUMMER),
AUTUMN=new Main(Season.AUTUMN),
WINTER=new Main(Season.WINTER);
SPRING.toString();
SUMMER.toString();
AUTUMN.toString();
WINTER.toString();
}
}
·使用自定义异常
自定以的异常继承父异常,使用方法也是调用父异常的方法,使用时抛出即可
class MyException extends Exception{
public MyException(String message){
super(message);
}
}
public class Solution {
public void validate(int num) throws MyException {
if (num>=0&&num<=100){
System.out.println(num);
}else
throw new MyException("The number you entered is not legal");
}
}
public class Main {
public static void main(String[] args) {
Solution solution = new Solution();
int num = Integer.parseInt(args[0]);
try {
solution.validate(num);
if ((num < 0) || (num > 100)) {
throw new RuntimeException("You need to throw a custom exception");
}
} catch (MyException e) {
System.out.println(e.getMessage());
}
}
}
·根据分数判断是否及格
根据输入的成绩判断即可
public class Solution {
public String scoreCompare(int score) {
if (score>=60){
return "passed";
}else
return "failed";
}
}
· 计算 n 以内包括 n 所有能被 3 整除的正整数的和
定义了Int i=3则使用while循环即可
public class Solution {
public int add(int number) {
int i = 3;
int sum = 0;
if (number<3)return 0;
while (i<=number){
if (i%3==0)
sum+=i;
i++;
}
return sum;
}
}
学习时间:
2021-8-21 16:00-18:00、19:00-22:30
学习产出:
刷题*6
学习笔记*1