Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 74af9ba

Browse files
authored
Merge pull request MisterBooo#95 from xiaoshuai96/master
solved @xiaoshuai96
2 parents 26d9265 + 1ce488f commit 74af9ba

File tree

4 files changed

+121
-0
lines changed

4 files changed

+121
-0
lines changed
Binary file not shown.
Loading
Loading
Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
## LeetCode第942号问题:增减字符串匹配
2+
3+
> 本文首发于公众号「图解面试算法」,是 [图解 LeetCode ](<https://github.com/MisterBooo/LeetCodeAnimation>) 系列文章之一。
4+
>
5+
> 同步个人博客:www.zhangxiaoshuai.fun
6+
7+
本题在leetcode中题目序号942,属于easy级别,目前通过率为71.4%
8+
9+
### 题目描述:
10+
11+
```
12+
给定只含 "I"(增大)或 "D"(减小)的字符串 S ,令 N = S.length。
13+
返回 [0, 1, ..., N] 的任意排列 A 使得对于所有 i = 0, ..., N-1,都有:
14+
如果 S[i] == "I",那么 A[i] < A[i+1]
15+
如果 S[i] == "D",那么 A[i] > A[i+1]
16+
17+
示例 1:
18+
输出:"IDID"
19+
输出:[0,4,1,3,2]
20+
21+
示例 2:
22+
输出:"III"
23+
输出:[0,1,2,3]
24+
25+
示例 3:
26+
输出:"DDI"
27+
输出:[3,2,0,1]
28+
29+
提示:
30+
1 <= S.length <= 10000
31+
S 只包含字符 "I" 或 "D"
32+
```
33+
34+
**题目分析:**
35+
36+
```
37+
题目中的意思很明确,我们只要满足给出的两个条件即可。
38+
39+
1.假如字符串的长度为N,那么目标数组的长度就为N+1;
40+
41+
2.数组中的数字都是从0~N,且没有重复;
42+
43+
3.遇见‘I’,要增加;遇见‘D’要减少;
44+
```
45+
46+
### GIF动画演示:
47+
48+
![](../Animation/0942-di-String-Match01.gif)
49+
50+
### 代码:
51+
52+
```java
53+
//这里搬运下官方的解法
54+
public int[] diStringMatch(String S) {
55+
int N = S.length();
56+
int lo = 0, hi = N;
57+
int[] ans = new int[N + 1];
58+
for (int i = 0; i < N; ++i) {
59+
if (S.charAt(i) == 'I')
60+
ans[i] = lo++;
61+
else
62+
ans[i] = hi--;
63+
}
64+
ans[N] = lo;
65+
return ans;
66+
}
67+
```
68+
69+
**虽然上述代码很简洁,好像已经不需要我们去实现什么;但是满足条件的序列并不止一种,官方的好像只能通过一种,下面的代码虽然有些冗余,但是得出的序列是满足题意要求的,但是并不能AC;**
70+
71+
### 思路:
72+
73+
```
74+
(1)如果遇见的是‘I’,那么对应数组当前位置的数字要小于它右边的第一个数字
75+
(2)如果遇见的是‘D’,那么对应数组当前位置的数字要大于它右边的第一个数字
76+
77+
首先对目标数组进行初始化,赋值0~N
78+
我们开始遍历字符串,如果遇见‘I’就判断对应数组该位置上的数是否满足(1)号条件
79+
如果满足,跳过本次循环;如果不满足,交换两个数字的位置;
80+
对于‘D’,也是同样的思路;
81+
```
82+
83+
### GIF动画演示:
84+
85+
![](../Animation/0942-di-String-Match02.gif)
86+
87+
### 代码:
88+
89+
```java
90+
public int[] diStringMatch(String S) {
91+
int[] res = new int[S.length()+1];
92+
String[] s = S.split("");
93+
for (int i = 0; i < res.length; i++) {
94+
res[i] = i;
95+
}
96+
for (int i = 0; i < s.length; i++) {
97+
if (s[i].equals("I")) {
98+
//判断指定位置的数字是否符合条件
99+
if (res[i] < res[i + 1]) {
100+
continue;
101+
} else {
102+
//交换两个数字的位置
103+
res[i] = res[i] ^ res[i+1];
104+
res[i+1] = res[i] ^ res[i+1];
105+
res[i] = res[i] ^ res[i+1];
106+
}
107+
} else {
108+
if (res[i] > res[i + 1]) {
109+
continue;
110+
} else {
111+
res[i] = res[i] ^ res[i+1];
112+
res[i+1] = res[i] ^ res[i+1];
113+
res[i] = res[i] ^ res[i+1];
114+
}
115+
}
116+
}
117+
return res;
118+
}
119+
```
120+
121+
**以上内容如有错误、不当之处,欢迎批评指正。**

0 commit comments

Comments
 (0)