当前位置:网站首页>优雅地翻转数组
优雅地翻转数组
2022-07-01 11:04:00 【tuhoooo】
引言
原文地址:优雅地翻转数组
欢迎访问我的博客: http://blog.duhbb.com/
感觉自己的代码写的不简洁, 而且容易出错, 搞得每次都很赶一样.
翻转的写法
题目很简单, 但是有个地方可以学习下: 就是数组翻转.
之前我喜欢这么写:
for (int k = j; k <= (i+j)/2; k++) {
char tmp = s[k];
s[k] = s[i - (k - j)];
s[i-(k-j)] = tmp;
}
今天看了 leetcode 上的解答, 原来这么写更优雅, for 循环写的看上去就比较复杂, 还容易出错.
int left = start, right = i - 1;
while (left < right) {
swap(s[left], s[right]);
left++;
right--;
}
#include <iostream>
#include <vector>
#include <climits>
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
string reverseWords(string s) {
int i = 0, j = 0;
while(true) {
while (s[i+1] != ' ' && s[i+1] != '\0') {
i++;
}
// 这个 for 循环写的就很丑, 而且还容易出错
for (int k = j; k <= (i+j)/2; k++) {
char tmp = s[k];
s[k] = s[i - (k - j)];
s[i-(k-j)] = tmp;
}
if (! s[i+1]) {
break;
}
i += 2;
j = i;
}
return s;
}
};
int main() {
Solution s;
cout << s.reverseWords("hello world") << endl;
return 0;
}
结束语
原文地址:优雅地翻转数组
欢迎访问我的博客: http://blog.duhbb.com/
写了再多的业务不注意提炼和总结, 感觉越写越迷糊, 其实停下来看看别人写的代码也许收获会更多.
边栏推荐
- PHP有哪些优势和劣势
- 个人商城二开逍遥B2C商城系统源码-可商用版/拼团拼购优惠折扣秒杀源码
- Submission lottery - light application server essay solicitation activity (may) award announcement
- Database experiment report (II)
- Exposure:A White-Box Photo Post-Processing Framework阅读札记
- LeetCode.515. 在每个树行中找最大值___逐一BFS+DFS+按层BFS
- PHP realizes lottery function
- Project0: Games
- Win平台下influxDB导出、导入
- 新品大揭秘!雅迪冠能 3 多元产品矩阵,满足全球用户出行需求
猜你喜欢

kubernetes之ingress探索实践

CVPR 2022 | 基于密度与深度分解的自增强非成对图像去雾

JS基础--数据类型

Infinite innovation in cloud "vision" | the 2022 Alibaba cloud live summit was officially launched

新品大揭秘!雅迪冠能 3 多元产品矩阵,满足全球用户出行需求

Intel Labs announces new progress in integrated photonics research

The exclusive collection of China lunar exploration project is limited to sale!

Cvpr22 | CMT: efficient combination of CNN and transformer (open source)

CVPR22 |CMT:CNN和Transformer的高效结合(开源)

数据库实验报告(一)
随机推荐
Compliance management of fund managers
What are the advantages and disadvantages of PHP
Harbor webhook从原理到构建
华为HMS Core携手超图为三维GIS注入新动能
Have the bosses ever done the operation of sink shunting and writing to Clickhouse or other databases.
[.net6] use ml.net+onnx pre training model to liven the classic "Huaqiang buys melons" in station B
毕业季·进击的技术er
我国蜂窝物联网用户已达 15.9 亿,年内有望超越移动电话用户
Mobile hard drive reads but does not display drive letter
Development overview of fund internationalization
名创拟7月13日上市:最高发行价22.1港元 单季净利下降19%
node版本管理器nvm安装及切换
In June 2022, it was the first programming language?!
CANN算子:利用迭代器高效实现Tensor数据切割分块处理
技术分享 | Linkis参数介绍
新品大揭秘!雅迪冠能 3 多元产品矩阵,满足全球用户出行需求
Huawei Equipment configure les services de base du réseau WLAN à grande échelle
The project bar on the left side of CodeBlocks disappears, workspace automatically saves the project, default workspace, open the last workspace, workspace (Graphic tutorial, solved)
Node version manager NVM installation and switching
Suggest collecting | what to do when encountering slow SQL on opengauss?