C++程序检查一个字符串是否可以通过最多X个循环顺时针移位从另一个字符串形成
给定一个整数X和两个字符串S1和S2 ,任务是通过将字符顺时针循环移动最多 X 次来检查字符串S1是否可以转换为字符串S2 。
Input: S1 = “abcd”, S2 = “dddd”, X = 3
Output: Yes
Explanation:
Given string S1 can be converted to string S2 as-
Character “a” – Shift 3 times – “d”
Character “b” – Shift 2 times – “d”
Character “c” – Shift 1 times – “d”
Character “d” – Shift 0 times – “d”
Input: S1 = “you”, S2 = “ara”, X = 6
Output: Yes
Explanation:
Given string S1 can be converted to string S2 as –
Character “y” – Circular Shift 2 times – “a”
Character “o” – Shift 3 times – “r”
Character “u” – Circular Shift 6 times – “a”
方法:想法是遍历字符串和对于每个索引,并找到两个字符串各自索引处字符的ASCII值之间的差异。如果差值小于 0,则对于循环移位,加 26 以获得实际差值。如果对于任何索引,差异超过X ,则S2不能从S1形成,否则可能。
下面是上述方法的实现:
C++
// C++ implementation to check
// that a given string can be
// converted to another string
// by circular clockwise shift
// of each character by atmost
// X times
#include
using namespace std;
// Function to check that all
// characters of s1 can be
// converted to s2 by circular
// clockwise shift atmost X times
void isConversionPossible(string s1,
string s2, int x)
{
int diff, n;
n = s1.length();
// Check for all characters of
// the strings whether the
// difference between their
// ascii values is less than
// X or not
for (int i = 0; i < n; i++) {
// If both the characters
// are same
if (s1[i] == s2[i])
continue;
// Calculate the difference
// between the ASCII values
// of the characters
diff = (int(s2[i] - s1[i])
+ 26)
% 26;
// If difference exceeds X
if (diff > x) {
cout << "NO" << endl;
return;
}
}
cout << "YES" << endl;
}
// Driver Code
int main()
{
string s1 = "you";
string s2 = "ara";
int x = 6;
// Function call
isConversionPossible(s1, s2, x);
return 0;
}
YES
时间复杂度: O(N),N=Length(S1)
辅助空间: O(1)
有关更多详细信息,请参阅有关检查一个字符串是否可以通过最多 X 个圆形顺时针移位从另一个字符串形成的完整文章!