检查是否可以将数字字符串拆分为具有等于 K 的连续数字之间的差异的子字符串
给定一个由N个数字和一个正整数K组成的数字字符串S ,任务是检查给定字符串是否可以拆分为多个子字符串,且连续子字符串之间的差异等于K。
例子:
Input: S = “8642”, K = 2
Output: Yes
Explanation: Split the given string as {“8”, “6”, “4”, “2”}. Now, the difference between the consecutive substrings is K(= 2).
Input: S = “1009896”, K = 0
Output: No
方法:给定问题可以通过生成给定字符串的所有可能子字符串来解决,并检查生成的子字符串的任何子集的连接是否等于给定字符串S并且作为子字符串的数字的连续差是K ,然后打印是。否则,打印No 。请按照以下步骤解决问题:
- 使用变量i迭代范围[1, N/2]并执行以下步骤:
- 存储长度为i并从0开始的子串 在变量X中。
- 从这个数字X开始生成大小为N的序列,其中连续项的差为K 。将此字符串存储在变量test中。
- 如果字符串test和S都相等,则将ans的值更新为true并跳出循环。
- 完成上述步骤后,如果ans的值为false ,则打印“No” 。否则,打印“是” 。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to check if a numeric string
// can be split into substrings such that
// the difference between the consecutive
// substrings is K
void isPossible(string s, int K)
{
bool valid = false;
long firstx = -1;
// Stores the size of the string
int n = s.length();
// Iterate over the range [1, N] and
// try each possible starting number
for (int i = 1; i <= n / 2; ++i) {
long x = stol(s.substr(0, i));
firstx = x;
// Convert the number to string
string test = to_string(x);
// Build up a sequence
// starting with the number
while (test.length() < s.length()) {
x -= K;
test += to_string(x);
}
// Compare it with the
// original string s
if (test == s) {
valid = true;
break;
}
}
// Print the result
cout << ((valid == true) ? "Yes " : "No");
}
// Driver Code
int main()
{
string S = "8642";
int K = 2;
isPossible(S, K);
return 0;
}
Python3
# python 3 program for the above approach
# Function to check if a numeric string
# can be split into substrings such that
# the difference between the consecutive
# substrings is K
def isPossible(s,K):
valid = False
firstx = -1
# Stores the size of the string
n = len(s)
# Iterate over the range [1, N] and
# try each possible starting number
for i in range(1,n//2+1,1):
x = int(s[0:i])
firstx = x
# Convert the number to string
test = str(x)
# Build up a sequence
# starting with the number
while (len(test) < len(s)):
x -= K
test += str(x)
# Compare it with the
# original string s
if (test == s):
valid = True
break
# Print the result
print("Yes") if valid == True else print("No")
# Driver Code
if __name__ == '__main__':
S = "8642"
K = 2
isPossible(S, K)
# This code is contributed by ipg2016107.
Javascript
输出:
Yes
时间复杂度: O(N 2 )
辅助空间: O(N)