classSolution{public:
string reorderSpaces(string text){int spaceCounts =0;
vector<string> v;for(int i =0; i < text.size(); i++){if(text[i]==' '){
spaceCounts++;continue;}int j = i +1;while(j != text.size()&& text[j]!=' ') j++;
v.push_back(text.substr(i, j - i));
i = j -1;}if(v.size()==1){
string ans = v[0];for(int i =0; i < spaceCounts; i++){
ans +=" ";}return ans;}int gap = spaceCounts /(v.size()-1);
string ga ="";for(int i =0; i < gap; i++){
ga +=" ";}
string ans ="";for(int i =0; i < v.size(); i++){if(i == v.size()-1){
ans += v[i];break;}
ans += v[i]+ ga;}int left = spaceCounts -(v.size()-1)* gap;for(int i =0; i < left; i++){
ans +=" ";}return ans;}};
1091. 二进制矩阵中的最短路径
代码实现(自解)
classSolution{public:intshortestPathBinaryMatrix(vector<vector<int>>& grid){int n = grid.size();
queue<pair<int,int>> myQueue;if(grid[0][0])return-1;
myQueue.push({0,0});int step =1;
vector<vector<int>> direction ={{1,0},{-1,0},{0,1},{0,-1},{1,1},{1,-1},{-1,1},{-1,-1}};
grid[0][0]=1;while(!myQueue.empty()){int sz = myQueue.size();while(sz--){auto[i, j]= myQueue.front();
myQueue.pop();if(i == n -1&& j == n -1){return step;}for(auto&v : direction){int x = v[0]+ i;int y = v[1]+ j;if(x <0|| y <0|| x >= n || y >= n){continue;}if(!grid[x][y]){
grid[x][y]=1;
myQueue.push({x, y});}}}
step++;}return-1;}};
542. 01 矩阵
代码实现(自解)
classSolution{public:
vector<vector<int>>updateMatrix(vector<vector<int>>& mat){
queue<pair<int,int>> myQueue;int m = mat.size();int n = mat[0].size();
vector<vector<int>>ans(vector(m,vector<int>(n)));for(int i =0; i < m; i++){for(int j =0; j < n; j++){if(!mat[i][j]){// cout << i << " " << j << endl;
myQueue.push({i, j});}}}int depth =1;
vector<pair<int,int>> direction ={{1,0},{-1,0},{0,1},{0,-1}};while(myQueue.size()){int sz = myQueue.size();while(sz--){auto[i, j]= myQueue.front();// cout << i << " " << j << endl;
myQueue.pop();for(auto[x, y]: direction){
x += i;
y += j;if(x <0|| y <0|| x >= m || y >= n){continue;}if(mat[x][y]){
mat[x][y]=0;// cout << i << " " << j << endl;
ans[x][y]= depth;
myQueue.push({x, y});}}}
depth++;}return ans;}};