每日两题2

目录

倒置字符串

题目介绍

题目分析

代码:

排序子序列

题目介绍

题目分析

代码:


倒置字符串

题目介绍

题目分析

分成两步解题:

1.将字符串化为字符数组后全部逆置。

2.将逆置后的字符数组中每个单词逆置,再将字符数组化为字符串后打印。

代码:

import java.util.*;
public class Main {
   //定义一个逆置数组的方法
    public static void reverse(char[] ch,int start,int end) {
        while (start < end) {
            char tmp = ch[start];
            ch[start] = ch[end];
            ch[end] = tmp;
            start++;
            end--;
        }
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        char[] ch = str.toCharArray();
        //整体进行逆置
        reverse(ch,0,ch.length - 1);
        int i = 0;
        //对每一个单词逆置
        while (i < ch.length) {
            int j = i;
            //让j下标早到空格且不数组越界
            while (j < ch.length && ch[j] != ' ') {
                j++;
            }
            if (j < ch.length) {
                reverse(ch,i,j - 1);
                //逆置一个单词后继续下一个单词
                i = j + 1;
            } else {
                reverse(ch,i,j - 1);
                i = j;
            }
        }
        String s = new String(ch);
        System.out.println(s);
    }
}

排序子序列

题目介绍

 

题目分析

理解非递增和非递减序列:

 1.从数组0下标开始遍历数组,定义count变量计算子序列的数目。

2.遍历过程中,如果数组元素有序或者前后元素相等的情况直接跳过,当数组元素出现改序情况的时候,则count++。

代码:

import java.util.*;
public class Main{
   public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        //数组多预留一个大小,防止后续array[i]和array[i+1]比较的时候数组越界
        int[] array = new int[n + 1];
        for (int i = 0; i < n; i++) {
            array[i] = sc.nextInt();
        }
        int i = 0;
        int count = 0;
        while (i < n) {
            if (array[i] < array[i + 1]) {
                //有序情况直接跳过,注意:设置i<n防止数组越界
                while (i < n && array[i] < array[i + 1]) {
                    i++;
                }
                //出现改序,子序列数加一
                i++;
                count++;
            } else if (array[i] == array[i + 1]) {
                i++;
            } else {
                    //有序情况直接跳过,注意:设置i<n防止数组越界
                    while (i < n && array[i] > array[i + 1]) {
                        i++;
                    }
                    //出现改序,子序列数加一
                    i++;
                    count++;
            }
        }
        System.out.println(count);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爆裂突破手

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值