用Qt编译无重复字符的最长子串求其长度包含界面
时间: 2024-05-10 21:14:54 浏览: 6
以下是一个使用Qt编写的求解最长无重复字符子串长度的界面程序示例:
1. 创建一个Qt窗口应用程序工程,并在主窗口中添加一个文本框用于输入字符串,一个按钮用于触发求解操作,以及另一个文本框用于显示结果。
2. 在按钮的槽函数中,获取用户输入的字符串,然后调用最长无重复字符子串的求解函数,并将结果显示在结果文本框中。
3. 下面是一个求解最长无重复字符子串长度的示例代码:
```cpp
int lengthOfLongestSubstring(string s) {
int n = s.size(), ans = 0;
unordered_map<char, int> mp;
for (int i = 0, j = 0; j < n; j++) {
if (mp.count(s[j])) {
i = max(i, mp[s[j]]);
}
ans = max(ans, j - i + 1);
mp[s[j]] = j + 1;
}
return ans;
}
```
其中,使用了一个哈希表(unordered_map)来记录每个字符最近出现的位置,使用双指针(i和j)来维护当前的子串,如果发现当前字符已经在子串中出现过,则将左指针i移到该字符最近出现的位置之后继续扫描,同时更新最长无重复字符子串的长度ans。
4. 将上述代码集成到Qt程序中,将用户输入的字符串作为函数的参数传递,将求解结果显示在文本框中即可。
以下是一个完整的示例程序:
```cpp
#include <QApplication>
#include <QWidget>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <string>
#include <unordered_map>
using namespace std;
int lengthOfLongestSubstring(string s) {
int n = s.size(), ans = 0;
unordered_map<char, int> mp;
for (int i = 0, j = 0; j < n; j++) {
if (mp.count(s[j])) {
i = max(i, mp[s[j]]);
}
ans = max(ans, j - i + 1);
mp[s[j]] = j + 1;
}
return ans;
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWidget *widget = new QWidget;
QVBoxLayout *layout = new QVBoxLayout;
QHBoxLayout *inputLayout = new QHBoxLayout;
QLabel *inputLabel = new QLabel("Input string:");
QLineEdit *inputLineEdit = new QLineEdit;
inputLayout->addWidget(inputLabel);
inputLayout->addWidget(inputLineEdit);
QHBoxLayout *buttonLayout = new QHBoxLayout;
QPushButton *button = new QPushButton("Calculate");
buttonLayout->addStretch();
buttonLayout->addWidget(button);
buttonLayout->addStretch();
QHBoxLayout *outputLayout = new QHBoxLayout;
QLabel *outputLabel = new QLabel("Length of longest substring:");
QLineEdit *outputLineEdit = new QLineEdit;
outputLineEdit->setReadOnly(true);
outputLayout->addWidget(outputLabel);
outputLayout->addWidget(outputLineEdit);
layout->addLayout(inputLayout);
layout->addLayout(buttonLayout);
layout->addLayout(outputLayout);
widget->setLayout(layout);
widget->show();
QObject::connect(button, &QPushButton::clicked, [&](){
string s = inputLineEdit->text().toStdString();
int length = lengthOfLongestSubstring(s);
outputLineEdit->setText(QString::number(length));
});
return a.exec();
}
```
该程序使用Qt提供的布局管理器(QHBoxLayout和QVBoxLayout)来实现界面布局,使用Lambda表达式来定义按钮的槽函数。在Qt Creator中编译并运行该程序,即可看到一个简单的求解最长无重复字符子串长度的界面程序。