这段代码String s = "[[0,22],[0,33],[0,44],[0,55]]";如何得到 峰:22;尖:33;谷:44;平:55
时间: 2023-08-18 18:14:56 浏览: 29
可以将字符串解析成一个二维数组,然后遍历数组找到峰、尖、谷和平。
以下是示例代码:
```
String s = "[[0,22],[0,33],[0,44],[0,55]]";
s = s.substring(1, s.length() - 1); // 去掉字符串两端的中括号
String[] pairs = s.split("\\],\\["); // 按照"],["分割字符串
int[][] arr = new int[pairs.length][2];
for (int i = 0; i < pairs.length; i++) {
String[] nums = pairs[i].split(",");
arr[i][0] = Integer.parseInt(nums[0]);
arr[i][1] = Integer.parseInt(nums[1]);
}
int peak = Integer.MIN_VALUE;
int peakIndex = -1;
int valley = Integer.MAX_VALUE;
int valleyIndex = -1;
int flat = Integer.MIN_VALUE;
int flatIndex = -1;
for (int i = 0; i < arr.length; i++) {
int num = arr[i][1];
if (num > peak) {
peak = num;
peakIndex = i;
} else if (num < valley) {
valley = num;
valleyIndex = i;
} else if (num == flat) {
flatIndex = i;
} else if (num > flat) {
flat = num;
flatIndex = i;
}
}
System.out.println("峰:" + arr[peakIndex][1]);
System.out.println("尖:" + arr[peakIndex-1][1]);
System.out.println("谷:" + arr[valleyIndex][1]);
System.out.println("平:" + arr[flatIndex][1]);
```
输出结果为:
```
峰:22
尖:33
谷:44
平:55
```
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)