编程题
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 -
解题思路:
- 本题依次比较整个数组
- a[i+1]>a[i] ,则进入非递增序列判断,直到遍历到下一个值不大于等于为止count++,然后进行下一位置的判断
- a[i+1]<a[i],则进入非递增序列判断,直到遍历到下一个值不小于等于为止count++,然后进行下一位置的判断
- 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);
}
}
- 结果