如果一个字符串是另一个字符串通过若干次移位产生的字串的子串,则输出YES,否则输出NO 输入样例: AABCD CDAA 输出样例: YES 输入样例: ABCD CDAA 输出样例: NO
时间: 2024-04-09 12:32:42 浏览: 13
可以使用以下的算法来解决这个问题:
1. 将第一个字符串复制一份,得到一个新的字符串temp。
2. 将temp与第二个字符串拼接在一起,得到一个新的字符串str。
3. 在str中查找第一个字符串的位置,如果找到了,则输出YES,否则输出NO。
下面是一个示例的Python代码实现:
```python
def is_substring(s1, s2):
temp = s1 + s1
if s2 in temp:
return "YES"
else:
return "NO"
s1 = input("请输入第一个字符串: ")
s2 = input("请输入第二个字符串: ")
print(is_substring(s1, s2))
```
你可以尝试运行这段代码,并输入示例中的输入样例进行测试。
相关问题
请用C++实现如果一个字符串是另一个字符串通过若干次移位产生的字串的子串,则输出YES,否则输出NO 输入样例: AABCD CDAA 输出样例: YES 输入样例: ABCD CDAA 输出样例: NO
您好!以下是使用 C++ 实现的代码:
```cpp
#include <iostream>
#include <string>
bool isSubstring(const std::string& s1, const std::string& s2) {
// 检查 s2 是否为 s1 的子串
return s1.find(s2) != std::string::npos;
}
bool isRotatedSubstring(const std::string& s1, const std::string& s2) {
if (s1.length() != s2.length()) {
return false;
}
std::string concatenated = s1 + s1; // 将 s1 连接自身
return isSubstring(concatenated, s2);
}
int main() {
std::string s1, s2;
std::cout << "请输入两个字符串:" << std::endl;
std::cin >> s1 >> s2;
if (isRotatedSubstring(s1, s2)) {
std::cout << "YES" << std::endl;
} else {
std::cout << "NO" << std::endl;
}
return 0;
}
```
这段代码中,我们定义了两个函数 `isSubstring` 和 `isRotatedSubstring`。`isSubstring` 函数用于判断字符串 `s2` 是否为字符串 `s1` 的子串,使用了 `std::string` 类中的 `find` 函数实现。`isRotatedSubstring` 函数则通过将字符串 `s1` 连接自身,再判断是否存在子串 `s2` 来判断是否为通过移位产生的子串。最后在 `main` 函数中获取用户输入的两个字符串,并调用 `isRotatedSubstring` 进行判断输出结果。
希望对您有所帮助!如有任何疑问,请随时提问。
如何用c语言判断一个字符串是另一个字符串的字串
可以使用strstr函数来判断一个字符串是否是另一个字符串的子串。该函数的原型如下:
```c
char *strstr(const char *str1, const char *str2);
```
其中,str1为要查找的字符串,str2为要查找的子串。如果str2是str1的子串,则该函数返回str2在str1中的首次出现的位置的指针;如果str2不是str1的子串,则该函数返回NULL。
下面是一个示例代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello, world!";
char str2[] = "world";
char *result = strstr(str1, str2);
if (result) {
printf("%s is a substring of %s\n", str2, str1);
} else {
printf("%s is not a substring of %s\n", str2, str1);
}
return 0;
}
```
输出结果为:
```
world is a substring of Hello, world!
```