题解 | #字符串是否由子串拼接#
字符串是否由子串拼接
https://www.nowcoder.com/practice/3c06901112f6465d859909f2601fccbd
解题思路
- 这是一个字符串首尾拼接问题,需要判断一个字符串是否由某个子串重复拼接而成
- 解题步骤:
- 将原字符串拼接自身得到双倍长度的字符串
- 去掉拼接后字符串的首尾字符
- 在处理后的字符串中查找原字符串
- 如果找到且位置在前半部分,则说明存在满足条件的子串
代码
#include <iostream>
#include <string>
using namespace std;
string findSubstring(string s) {
int n = s.length();
// 将字符串拼接自身并去掉首尾
string doubled = s + s;
string trimmed = doubled.substr(1, 2 * n - 2);
// 在处理后的字符串中查找原字符串
size_t pos = trimmed.find(s);
if(pos != string::npos && pos < n) {
return s.substr(0, pos + 1);
}
return "false";
}
int main() {
string s;
cin >> s;
cout << findSubstring(s) << endl;
return 0;
}
import java.util.Scanner;
public class Main {
public static String findSubstring(String s) {
int n = s.length();
// 将字符串拼接自身并去掉首尾
String doubled = s + s;
String trimmed = doubled.substring(1, 2 * n - 1);
// 在处理后的字符串中查找原字符串
int pos = trimmed.indexOf(s);
if(pos != -1 && pos < n) {
return s.substring(0, pos + 1);
}
return "false";
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
System.out.println(findSubstring(s));
}
}
def find_substring(s):
n = len(s)
# 将字符串拼接自身并去掉首尾
doubled = s + s
trimmed = doubled[1:2*n-1]
# 在处理后的字符串中查找原字符串
pos = trimmed.find(s)
if pos != -1 and pos < n:
return s[:pos+1]
return "false"
s = input()
print(find_substring(s))
算法及复杂度
- 算法:字符串匹配
- 时间复杂度:
-
为字符串长度
- 空间复杂度:
- 需要存储拼接后的字符串