刷leetcode的第一道题——Reverse Words in a String
来源:互联网 发布:java工程师的报考条件 编辑:程序博客网 时间:2024/06/09 19:19
好久没在Online Judge上做题了,今晚7点就要做阿里校招的在线笔试了,前两个多小时去leetcode做了一道字符串的题,好多潜在的trick,还好在WA了两次后终于AC了。
Leetcode第一题Reverse Words in a String,题目很简单:
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
1、前导和后导空格需要去掉,中间多个空格只能保留一个(话说这还是我上次实习面有道的一道题目)
2、字符串只有空格时,返回""
下面贴上代码,基本上用到的字符串函数都是自己手动实现的(除memmove外),Leetcode的接口居然定义的是string,下面代码的实现都是char*
class Solution {public: void reverseWords(string &s) { if(s.length() == 0 || s == " "){ s = ""; return; } int cnt = 0; for(int i = 0 ; i < s.length(); i ++){ if(s[i] == ' ') cnt ++; else break; } if(cnt == s.length()){ s = ""; return; } char str[10240]; strcpy(str ,s.c_str()); strtrim(str); int len = strlength(str); int begin = 0; for (int i = 0; i < len; i ++) { if (str[i] == ' ') { reverse(str,begin,i - 1); begin = i + 1; } } reverse(str, begin, len - 1); reverse(str,0,len-1); for (int i = 0; i < len ; i ++) { s[i] = str[i]; } s.resize(len); } int strlength(const char *str){ const char *pstr = str; while (*pstr ++ != '\0'); return pstr - str - 1; } void swap(char &a,char &b) { char tmp = a; a = b; b = tmp; } void strtrim(char *str){//去除空格 char *pstr = str; int len = strlen(str); int from = 0, to = 0; while(*pstr == ' ') { pstr++; from ++; } pstr = str + len - 1; while(*pstr == ' ') { pstr --; to ++; } memmove(str,str+from,len - from - to); *(str + len - from - to) = '\0'; pstr = str; char *ts = str; while(*pstr != '\0'){ if(*pstr != ' '){ *ts = *pstr; ts++; pstr++; }else{ while(*pstr == ' ') pstr ++; *ts ++ = ' '; } } *(ts++) = '\0'; } void reverse(char *str, int from, int to) { char *pbegin = str + from; char *pend = str + to; while (pbegin <= pend) { swap(*pbegin++, *pend --); } }};
0 0
- 刷leetcode的第一道题——Reverse Words in a String
- Leetcode 第151题 Reverse Words in a String
- [LeetCode 第3题] -- Reverse Words in a String
- LeetCode刷题笔录Reverse Words in a String
- LeetCode——Reverse Words in a String
- LeetCode——Reverse Words in a String
- LeetCode——Reverse Words in a String
- leetcode 151 —— Reverse Words in a String
- Reverse Words in a String —— Leetcode
- LeetCode题解——Reverse Words in a String
- Leetcode——151. Reverse Words in a String
- LeetCode——557. Reverse Words in a String III
- LeetCode 之 Reverse Words in a String — C 实现
- Leetcode - string - Reverse Words in a String
- LeetCode151—Reverse Words in a String
- Reverse words in a String leetcode
- [LeetCode]Reverse Words in a String
- 【LeetCode】Reverse Words in a String
- 二叉树的镜像
- 比较好的JavaScript库-日常备用
- Android动态加载APK问题整理
- Hadoop网络课程模板程序
- Cocos2d-x 3.0 开发(九)使用Physicals代替Box2D和chipmunk
- 刷leetcode的第一道题——Reverse Words in a String
- android ICS 系统启动之Logo有关学习总结
- Cocos2d-x 3.0 开发(八)骨骼动画的动态换肤
- platform_driver_probe与platform_driver_register的区别
- cocos2dx面试题(2)
- Unrecognized Windows Sockets error: 0: JVM_Bind 异常解决办法
- maven实用命令
- 黑马程序员 C语言 - 01 第一个C语言程序、基本知识
- hdu2955 - Robberies