给定大小为N的二进制字符串S ,任务是检查是否可以通过删除任意数量的不相邻字符来对二进制字符串S进行降序排序。如果可以按降序对字符串进行排序,则打印“是” 。否则,打印“否” 。
例子:
Input: S = “10101011011”
Output: Yes
Explanation:
After removing the non-adjacent characters at indices 1, 3, 5, and 8 modifies the string to “1111111”, which is sorted in decreasing order. Therefore, print “Yes”.
Input: S = “0011”
Output: No
方法:可以基于以下观察结果解决给定的问题:如果存在两个相邻的字符(具有1) ,然后存在相邻的字符(具有0) ,则无法通过除去不相邻的字符来对字符串进行排序。请按照以下步骤解决问题:
- 初始化一个布尔变量,说为true的标志存储状态是否给定的字符串可以排序。
- 从末尾遍历给定的字符串S ,如果存在一对相邻的字符,其值均为1s,则将第二个索引1存储在变量idx中,并退出循环。
- 在范围[idx,0]范围内从背面再次遍历给定的字符串S ,如果存在相邻的成对的相邻字符对,其值均为0s,则将flag的值更新为false并退出循环。
- 完成上述步骤后,如果flag的值为true ,则打印“ Yes” 。否则,打印“否” 。
下面是上述方法的实现:
C++
// C++ programm for the above appraoch
#include
using namespace std;
// Function to sort the given string in
// decreasing order by removing the non
// adajcent characters
string canSortString(string S, int N)
{
// Keeps the track whether the
// string can be sorted or not
int flag = 1;
int i, j;
// Traverse the given string S
for (i = N - 2; i >= 0; i--) {
// Check if S[i] and
// S[i + 1] are both '1'
if (S[i] == '1'
&& S[i + 1] == '1') {
break;
}
}
// Traverse the string S from
// the indices i to 0
for (int j = i; j >= 0; j--) {
// If S[j] and S[j + 1] is
// equal to 0
if (S[j] == '0'
&& S[j + 1] == '0') {
// Mark flag false
flag = 0;
break;
}
}
// If flag is 0, then it is not
// possible to sort the string
if (flag == 0) {
return "No";
}
// Otherwise
else {
return "Yes";
}
}
// Driver Code
int main()
{
string S = "10101011011";
int N = S.length();
cout << canSortString(S, N);
return 0;
}
Python3
# Python3 program for the above appraoch
# Function to sort the given string in
# decreasing order by removing the non
# adajcent characters
def canSortString(S, N):
# Keeps the track whether the
# string can be sorted or not
flag = 1
# Traverse the given string S
i = N - 2
while(i >= 0):
# Check if S[i] and
# S[i + 1] are both '1'
if (S[i] == '1' and S[i + 1] == '1'):
break
i -= 1
# Traverse the string S from
# the indices i to 0
j = i
while(j >= 0):
# If S[j] and S[j + 1] is
# equal to 0
if (S[j] == '0' and S[j + 1] == '0'):
# Mark flag false
flag = 0
break
j -= 1
# If flag is 0, then it is not
# possible to sort the string
if (flag == 0):
return "No"
# Otherwise
else:
return "Yes"
# Driver Code
if __name__ == '__main__':
S = "10101011011"
N = len(S)
print(canSortString(S, N))
# This code is contributed by ipg2016107
输出:
Yes
时间复杂度: O(N)
辅助空间: O(1)