1.求最长非重复字符串长度
分析:做个hash_table表,记录每个字符的位置。
pre记录第一个不重复的字符的位置。
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
int process(string data)
{
vector<int>hash_table(256,-1);
int pre = 0;
int max_len = 0;
for (int i = 0; i <data.size(); ++i)
{
if (hash_table[data[i]] != -1)
pre = hash_table[data[i]] + 1;
hash_table[data[i]] = i;
max_len = max(max_len, i - pre + 1);
}
return max_len;
}
int main()
{
string data = "abcdefga";
cout<<process(data);
system("pause");
return 0;
}
2.给定一个M*M的二维数组,每个值1的元素代表一个团队。如果两个团队在上下或左右的方向上相邻,说明2个团队有联系,就要把他们合并到一个部门;没有联系的,就放在不同部门。
判断输入中,有多少个部门。
输入:
第一行,一个整数,M
后面M行,每行M个整数(取值0或者1)
输出:
一个整数,部门数
样例输入:
1 0 0 1 1
1 0 0 1 1
0 0 1 0 0
0 0 1 0 0
0 0 1 0 0
样例输出:
3
提示:
左上角有一个部门,右上角有一个部门,下面有一个部门。
分析:使用dfs算法,每次遍历到1后把当前和相邻的1都置为0;
#include<iostream>
#include<vector>
using namespace std;
void dfs(vector<vector<int> > &data,int x,int y,int row,int col)
{
if (x<0 || y<0 || x>=row || y>=col || data[x][y] == 0)
return;
data[x][y] = 0;
dfs(data, x - 1, y, row, col);
dfs(data, x, y - 1, row, col);
dfs(data, x + 1, y, row, col);
dfs(data, x, y + 1, row, col);
}
int main()
{
vector<vector<int> >data =
{ {1, 0, 0, 1, 1},
{1, 0 ,0, 1, 1},
{0, 0 ,1, 0, 0},
{0, 0 ,1, 0, 0},
{0, 0 ,1, 0, 0} };
int row = data.size();
int col = data[0].size();
int sum = 0;
for (int i = 0; i < row; ++i)
{
for (int j = 0; j < col; ++j)
if (data[i][j] == 1)
{
sum += 1;
dfs(data, i, j, row, col);
}
}
cout << sum << endl;
system("pause");
return 0;
}
4.ip地址中的“.”漏掉了,试图恢复,问有多少个正确的ip数量。
思路:深度优先。不符合则回溯。
#include <iostream>
#include <string>
#include <vector>
using namespace std;
bool isValid(string s) {
if (s.size() > 1)
return s[0] != '0'&&stoi(s) >= 0 && stoi(s) < 256;
return stoi(s) >= 0 && stoi(s)< 256;
}
void DFS(string t, string s, vector<string>& result, int count) {
if (count == 3 && isValid(s)) {
result.push_back(t + s);
return;
}
for (int i = 1; i < 4 && i < s.size(); i++) {
string sub = s.substr(0, i);
if (isValid(sub)) {
DFS(t + sub + ".", s.substr(i), result, count + 1);
}
}
}
int restoreIpAddresses(string s) {
vector<string> result;
string t;
DFS(t, s, result, 0);
return result.size();
}
int main()
{
string s;
cin >> s;
cout << restoreIpAddresses(s) << endl;
system("pause");
return 0;
}