每日代码练习

代码段(一)

  • 问题 1:如果字符串S的第i个字符是'R', 'G', 'B'或'Y',那么第i块瓷砖的颜色就分别代表是红、绿、蓝或者黄. 牛牛决定换掉一些瓷砖的颜色,使得相邻两块瓷砖的颜色均不相同。

  • 思路:如果两块相邻两块瓷砖相同,那么必定需要代替掉一块的。假如i遍历到A,发现B与A的颜色一样的,那么AB直接必定有一块需要更替,这时候i的遍历要跳过B,从C继续判断。

public class problem1 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            String next = sc.next();
            char[] arr = next.toCharArray();
            int result = 0;
            for(int i=0;i
  • 问题 2:DNA序列指的是序列中只包括'A','T','C','G',例如: s = "ABCBOATER"中包含最长的DNA片段是"AT",所以最长的长度是2。

  • 思路:题干中只说明了DNA的序列的组成,没说明'A','T','C','G'的顺序,所以可以用一个IF来判断遍历的数组中最长的序列

public class problem2 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str= sc.next();
        char[] arr = str.toCharArray();
        int result = 0;
        int max = 0;
        for(int i=0;i
  • 问题 3:从末尾删除字母之后仍然是偶串,最长的偶串,主要这个break很关键。例如"xyzxyz"和"aaaaaa"是偶串,但是"ababab"和"xyzxy"却不是。

  • 思路:每一次删除偶串必定删除两个, 所以可以从中间开始,每次减一。之后截取字符串进行比较,break很关键--用于截取最长的

public class problem3 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str= sc.next();
        int result = 0;
        for(int i = str.length() / 2 - 1 ; i > 0 ; i--){
            String str1 = str.substring(0,i);
            String str2 = str.substring(i,i*2);
            if(str1.equals(str2)){
                result=2*i;
                break;
            }
        }
        System.out.println("所得数组的长度为: "+result);
    }
}
  • 问题 4:判断一串字符最少能组成几组的回文数,例如: s = "abbaa",输出1,因为最少可以拼凑出"ababa"这一个回文串s = "abc", 输出3,因为最少只能拼凑出"a","b","c"这三个回文串

  • 思路:用一个map统计下每个字符出现的次数,字符作为key,通过getValues的方式获得值,假如值为偶数,那么可以组成回文,若有多少个奇数,则有多少组回文。

public class problem4 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.next();
        char[] arr = str.toCharArray();
        int result =0;
        Map map = new HashMap<>();
        for(int i=0;i
  • 问题 5:给你一个N,你想让其变为一个Fibonacci数,每一步你可以把当前数字X变为X-1或者X+1,现在给你一个数N求最少需要多少步可以变为Fibonacci数。
public class Fibonacci {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();
        int a=0,b=1;
        while(b<=num){
            int temp = a+b;
            a=b;
            b=temp;
        }
        System.out.println((b-num)>(num-a)?num-a:b-num);
    }
}

你可能感兴趣的:(每日代码练习)