牛客网每日一题_Java方向编程题——第一周DAY2_20210413

编程题

1.69389-倒置字符串

  • 牛客网链接
    将一句话的单词进行倒置,标点不倒置。比如 I like beijing. 经过函数后变为:beijing. like I
  • Java代码实现

import java.util.Scanner;

public class Main{

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String s = scanner.nextLine();
        char[] ch = s.toCharArray();
        int len = ch.length;
        //1.整体进行逆置
        reverse(ch,0,len-1);
        int i = 0;// 遍历 ch 数组
        while (i < len) {
            int j = i;
            while (j < len && ch[j] != ' ') {
                j++;
            }
            if (j < len) {
                reverse(ch,i,j-1);
                i = j + 1;
            } else {
                reverse(ch,i,j-1);
                i = j;
            }
        }
        String str = new String(ch);
        System.out.println(str);
    }
    public static void reverse(char[] array,int start,int end) {
        while (start < end){
            char tem = array[start];
            array[start] = array[end];
            array[end] = tem;
            start++;
            end--;
        }
    }
}

  • 结果

在这里插入图片描述

2. 100448 排序子序列

  • 牛客网链接
    牛牛定义排序子序列为一个数组中一段连续的子序列,并且这段子序列是非递增或者非递减排序的。牛牛有一个长度为n的整数数组A,他现在有一个任务是把数组A分为若干段排序子序列,牛牛想知道他最少可以把这个数组分为几段排序子序列.
    如样例所示,牛牛可以把数组A划分为[1,2,3]和[2,2,1]两个排序子序列,至少需要划分为2个排序子序列,所以输出2

  • 解题思路:

  1. 本题依次比较整个数组
  2. a[i+1]>a[i] ,则进入非递增序列判断,直到遍历到下一个值不大于等于为止count++,然后进行下一位置的判断
  3. a[i+1]<a[i],则进入非递增序列判断,直到遍历到下一个值不小于等于为止count++,然后进行下一位置的判断
  4. a[i+1] == a[i]不进行操作,++i进行下一位置遍历,因为相等既可以属于非递增序列,也可以属于非递减序列。
  • Java代码实现


import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int[] array = new int[n + 1];
        for (int i = 0; i < n; i++) {
            array[i] = scanner.nextInt();
        }
        int count = 0;
        int i = 0;
        while (i < n) {
            if (array[i] < array[i + 1]) {
                while (i < n && array[i] <= array[i + 1]) {
                    i++;
                }
                count++;
                i++;
            } else if (array[i] == array[i + 1]) {
                i++;
            } else {
                while (i < n && array[i] >= array[i + 1]){
                    i++;
            }
            count++;
            i++;
        }
    }
        System.out.println(count);
}
    }



  • 结果
    在这里插入图片描述
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值