本文主要是介绍9.20(54. 螺旋矩阵 71. 简化路径),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
54. 螺旋矩阵
本题比较简单,详情见代码
程序代码:(完整版)
#include <iostream>
#include<vector>
#include<algorithm>
#include<string>
//54.螺旋矩阵
using namespace std;class Solution {
public:vector<int> spiralOrder(vector<vector<int>>& matrix) {vector<int> result;//结果都存放在这里面int m = matrix.size();if(m==0) return result;//就返回空的int n = matrix[0].size(); int i1 = 0, i2 = m - 1, j1 = 0, j2 = n - 1;//这个标志了四个边界while (i1<i2&&j1<j2) {int j = j1;while (j < j2) { result.push_back(matrix[i1][j]); j++; }int i = i1;while (i < i2) { result.push_back(matrix[i][j2]); i++; }j = j2;//初始化数值while (j > j1) { result.push_back(matrix[i2][j]); j--; }i = i2;while (i > i1) { result.push_back(matrix[i][j1]); i--; }i1++, j1++, i2--, j2--;//向中心靠近}if (i1 == i2) {int j = j1;while (j <= j2) { result.push_back(matrix[i1][j]); j++; }}else if (j1 == j2) {int i = i1;while (i <= i2) { result.push_back(matrix[i][j1]); i++; }}else if(i1 == i2&& j1 == j2)result.push_back(matrix[i1][j1]);return result;}
};int main()
{Solution bb;int m,n;cin >> m >> n;vector<vector<int>> matrix;for (int i = 0; i < m; i++) {vector<int> vec;for (int j = 0; j < n; j++) {int tmp;cin >> tmp;vec.push_back(tmp);}matrix.push_back(vec);}vector<int> result = bb.spiralOrder(matrix);for (int e : result) {cout<<e<<" ";}return 0;
}
测试时出现了一个错误,就是没有针对空集的特殊处理。
加上就可以了。
71. 简化路径
本题运行不成功,不知道为什么,感觉题目中的错误例子举的也不好
程序代码:
#include <iostream>
#include<vector>
#include<algorithm>
#include<string>
#include<stack>//引入数据结构堆栈
//71、这个题目是一个次序解决的问题
using namespace std;class Solution {
public:string simplifyPath(string path) {int i = 0;//控制字符串长度的变量stack<int> stack;string result = "";if (path == "/..")return result;while (i<path.size()) {if (stack.size() == 0) stack.push(path[i++]);else if (path[i] == '/'&&stack.top() == '/') i++;else if (path[i] != '.'&&stack.top() == '.') {while (stack.top() != '/')stack.pop();stack.pop();//最后还要将本身的那个‘/’pop出去}else if (path[i] == '.'&&stack.top() == '.') {i++;int count = 0;while (1) {if (stack.top() == '/') count++;stack.pop();if (count == 2||stack.size()==0)break;}}else stack.push(path[i++]);}if (stack.size()!=1&&stack.top() == '/') stack.pop();int n = stack.size();//堆栈的尺寸while (stack.size() != 0) {result.insert(result.begin(),stack.top());//可以插入字符,表示在最前面插入字符stack.pop();}return result;}
};int main()
{Solution bb;string path;cin >> path;string result = bb.simplifyPath(path);cout<<result<<endl;return 0;
}
样例通过率是226/252。我也不知道是为啥了,给出来的反例都很奇怪
参考程序链接:
https://blog.csdn.net/qq_17550379/article/details/80802176
这篇关于9.20(54. 螺旋矩阵 71. 简化路径)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!