目录
倒置字符串
题目介绍
题目分析
分成两步解题:
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);
}
}