运用C++语言编程实现“顺序串”,并实现其上的基本操作。要求:(1)定长顺序串或堆式顺序串二选一;(2)实现串的创建(初始化)、清空、串的赋值、输出以及求子串、查找子串以及删除子串的操作;(3)查找子串的算法自选。
时间: 2024-12-04 20:25:21 浏览: 5
数据结构串的存储结构程序
在C++中,我们可以选择使用定长顺序串(固定大小数组实现),因为这比较简单直观。下面是一个基础的实现示例:
```cpp
#include <iostream>
using namespace std;
#define SIZE 10 // 定义串的最大长度
// 顺序串的结构体
struct SequenceString {
char data[SIZE]; // 存储字符的数组
int length; // 当前字符串的实际长度
};
// 初始化顺序串
SequenceString initSequenceString(const string& str) {
SequenceString seq;
seq.length = min(str.size(), SIZE);
for (int i = 0; i < seq.length; ++i)
seq.data[i] = str[i];
return seq;
}
// 清空顺序串
void clear(SequenceString& seq) {
seq.length = 0;
}
// 赋值操作
void assign(SequenceString& seq, const SequenceString& other) {
if (seq.length + other.length > SIZE)
throw "Overflow";
for (int i = 0; i < other.length; ++i)
seq.data[seq.length + i] = other.data[i];
seq.length += other.length;
}
// 输出顺序串
void output(const SequenceString& seq) {
for (int i = 0; i < seq.length; ++i)
cout << seq.data[i];
cout << endl;
}
// 求子串
SequenceString substr(const SequenceString& seq, int start, int end) {
if (start < 0 || start >= seq.length || end > seq.length || start > end)
throw "Invalid index";
SequenceString sub;
sub.length = end - start;
for (int i = 0; i < sub.length; ++i)
sub.data[i] = seq.data[start + i];
return sub;
}
// 查找子串(例如使用KMP算法)
int findSubstring(const SequenceString& text, const SequenceString& pattern) {
int n = text.length;
int m = pattern.length;
int kmpTable[m];
buildKMP(pattern, kmpTable);
int j = 0;
for (int i = 0; i < n; ++i) {
while (j > 0 && text.data[i] != pattern.data[j])
j = kmpTable[j - 1];
if (text.data[i] == pattern.data[j])
j++;
if (j == m)
return i - m + 1;
}
return -1;
}
// KMP表构建函数
void buildKMP(const SequenceString& pattern, int* kmpTable) {
kmpTable[0] = -1;
int j = -1;
for (int i = 1; i < pattern.length; ++i) {
while (j > -1 && pattern.data[i] != pattern.data[j + 1])
j = kmpTable[j];
if (pattern.data[i] == pattern.data[j + 1])
j++;
kmpTable[i] = j;
}
}
阅读全文