当前位置:网站首页>优雅地翻转数组
优雅地翻转数组
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/
写了再多的业务不注意提炼和总结, 感觉越写越迷糊, 其实停下来看看别人写的代码也许收获会更多.
边栏推荐
- Internal control of fund managers
- [paper reading] trajectory guided control prediction for end to end autonomous driving: a simple yet strong Ba
- "Target detection" + "visual understanding" to realize the understanding and translation of the input image (with source code)
- Node version manager NVM installation and switching
- Matplotlib data visualization Foundation
- Oracle和JSON的结合
- Huawei Equipment configure les services de base du réseau WLAN à grande échelle
- 华泰证券网上开户安全吗?
- I'd like to know where I can open an account in Guangzhou? Is it safe to open an account online now?
- 数据库实验报告(一)
猜你喜欢
英特爾實驗室公布集成光子學研究新進展
Rising Stars in Plant Sciences (RSPS2022) Finalist科学演讲会(6.30晚9点)
What are the advantages and disadvantages of PHP
Intel Labs annonce de nouveaux progrès en photonique intégrée
China's cellular Internet of things users have reached 1.59 billion, and are expected to surpass mobile phone users within this year
移动硬盘驱动器读到,但不显示盘符
京东与腾讯续签合作:向腾讯发行A类股 价值最高达2.2亿美元
中国探月工程独家藏品限量发售!
Combinaison Oracle et json
Technology sharing | introduction to linkis parameters
随机推荐
2022年已经过去一半了,是不是很突然呢?
Get key code
十年磨一剑:蚂蚁集团可观测性平台 AntMonitor 揭秘
CPI教程-异步接口创建及使用
金鱼哥RHCA回忆录:DO447使用Ansible与API通信--使用Ansible Tower API启动作业
华泰证券网上开户安全吗?
华为设备配置大型网络WLAN基本业务
Mutual conversion of pictures in fluent uint8list format and pictures in file format
转义字符串
银行卡借给别人是否构成犯罪
个人商城二开逍遥B2C商城系统源码-可商用版/拼团拼购优惠折扣秒杀源码
《数据安全法》出台一周年,看哪四大变化来袭?
【AI资讯月刊】350+资源大盘点!6月不容错过的资料和动态,都都都在这里啦!<附下载>
LeetCode 438. 找到字符串中所有字母异位词__滑动窗口
获取键代码
Database experiment report (I)
MIT's latest paper, "the need for interpretable features: motivation and classification": building interpretability in the constituent elements of machine learning models
PHP有哪些优势和劣势
[.net6] use ml.net+onnx pre training model to liven the classic "Huaqiang buys melons" in station B
Prism journal navigation button usability exploration record