华为笔试 c++ AC 2.6 代码
字符串拆分 ac
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin >> n;
vector<string> strs(n);
for(int i = 0 ;i < n;i++)
{
cin >> strs[i];
}
multiset<string> ans;
for(int i = 0;i < n;i++)
{
int nowSize = strs[i].size();
//需要拆分
if(nowSize > 8){
int index = 0;
while(nowSize > 8)
{
string now = strs[i].substr(index, 8);
ans.insert(now);
index += 8;
nowSize -= 8;
}
string zero = "";
for(int j = 0;j < 8 - nowSize;j++){
zero += "0";
}
string now = strs[i].substr(index,nowSize);
ans.insert(now + zero);
}
else{
string zero = "";
string now = strs[i].substr(0,nowSize);
for(int j = 0;j < 8 - nowSize;j++){
zero += "0";
}
ans.insert(now + zero);
}
}
for(auto it = ans.begin(); it != ans.end();it++)
cout << *it << " ";
return 0;
}
字符串括号 ac
LeetCode 394 原题改编
#include<bits/stdc++.h>
using namespace std;
string decodeString(string s) {
string res = "", t = "";
stack<int> s_num;
stack<string> s_str;
int cnt = 0;
for (int i = 0; i < s.size(); ++i) {
if (s[i] >= '0' && s[i] <= '9') {
cnt = 10 * cnt + s[i] - '0';
} else if (s[i] == '(' || s[i] == '[' || s[i] == '{') {
s_num.push(cnt);
s_str.push(t);
cnt = 0; t.clear();
} else if (s[i] == ')' || s[i] == ']' || s[i] == '}') {
int k = s_num.top(); s_num.pop();
for (int j = 0; j < k; ++j) s_str.top() += t;
t = s_str.top(); s_str.pop();
} else {
t += s[i];
}
}
return s_str.empty() ? t : s_str.top();
}
int main()
{
string str;
cin >> str;
str = decodeString(str);
for(int i = str.size() - 1;i >= 0;i--)
cout << str[i];
cout << endl;
}
海拔 63%样例
dfs遍历,注意边界条件。
#include<bits/stdc++.h>
using namespace std;
long long maxnum = 1e9;
void DFS(vector<vector<long long> > &grid, vector<vector<bool> > &visited, int x, int y, int z, int w, int& ans) {
if (x < 0 || x >= grid.size()) return;
if (y < 0 || y >= grid[0].size()) return;
if(x == z && y == w){
ans++;
return;
}
int now = grid[x][y];
if (visited[x][y]) return;
visited[x][y] = true;
if(x - 1 >=0 && grid[x - 1][y] > now )DFS(grid, visited, x - 1, y, z, w, ans);
if(x + 1 < grid.size() && grid[x + 1][y] > now )DFS(grid, visited, x + 1, y, z, w, ans);
if(y - 1 >= 0 && grid[x][y - 1] > now )DFS(grid, visited, x, y - 1, z, w, ans);
if(y + 1 <= grid[0].size() && grid[x][y + 1] > now )DFS(grid, visited, x, y + 1, z, w, ans);
visited[x][y] = false;
}
int main()
{
int n,m;
cin >> n >> m;
vector< vector<long long> > g(n, vector<long long>(m, 0));
vector<vector<bool> > visited(n, vector<bool>(m, false));
for(int i = 0;i < n;i++){
for(int j = 0; j < m;j++)
cin >> g[i][j];
}
int x,y,z,w;
cin >> x >> y >> z >> w;
int ans = 0;
DFS(g, visited, x, y, z, w, ans);
ans = ans%maxnum;
cout << ans << endl;
return 0;
}
有没有第三题ac的大佬啊,dfs时间复杂度太高了。
#笔试题目##华为#