String: 58. Length of Last Word
来源:互联网 发布:如何优化dnf非常流畅 编辑:程序博客网 时间:2024/06/03 21:21
这个题这么简单,但是调了好久,最后直接求结果没调好,无奈申请了一个string存放结果,再返回string的长度。
class Solution {public: int lengthOfLastWord(string s) { string result = ""; int i = s.size() - 1; while(s[i] == ' ' && i >= 0) { i--; } while(s[i] != ' ' && i >= 0) { result = s[i] + result; i--; } cout << result << endl; return result.size(); }};但是看了别人写的,发现自己真是蠢……脑子不会转弯…………不用string当然也可以啊,之前总想着定义一个start一个end,但是发现要分情况讨论start和end,又会产生很多if,又容易出错。应该这样就可以:
class Solution {public: int lengthOfLastWord(string s) { int len = 0; int i = s.size() - 1; while(s[i] == ' ' && i >= 0) { i--; } while(s[i] != ' ' && i >= 0) { len++; i--; } return len; }};
阅读全文
0 0
- String: 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- 58. Length of Last Word
- [LeetCode] Container With Most Water
- [LeetCode] Count and Say
- [LeetCode] Combinations
- [LeetCode] 4Sum
- [LeetCode] Combination Sum II
- String: 58. Length of Last Word
- [LeetCode] Combination Sum
- [LeetCode] Best Time to Buy and Sell Stock II
- [LeetCode] Best Time to Buy and Sell Stock III
- [LeetCode] Edit Distance
- [LeetCode] Flatten Binary Tree to Linked List
- [LeetCode] Gray Code
- [LeetCode] Decode Ways
- [LeetCode] Generate Parentheses