首页 > 其他 > 详细

Leetcode(58)题解:Length of Last Word

时间:2015-08-06 22:05:47      阅读:227      评论:0      收藏:0      [点我收藏+]

https://leetcode.com/problems/length-of-last-word/

题目:

Given a string s consists of upper/lower-case alphabets and empty space characters ‘ ‘, return the length of last word in the string.

If the last word does not exist, return 0.

Note: A word is defined as a character sequence consists of non-space characters only.

For example, 
Given s = "Hello World",
return 5.

思路:

主要是确定最后一个单词的边界。注意特殊情况。

AC代码:

 1 class Solution {
 2 public:
 3     int lengthOfLastWord(string s) {
 4         int begin=-1,end=-1,j,n=s.size();
 5         for(j=n-1;j>=0;j--)
 6             if(s[j]!= ){
 7                 begin=j;
 8                 break;
 9             }
10         if(begin==-1)
11             return 0;
12         for(j=begin;j>=0;j--){
13             if(s[j]== ){
14                 end=j+1;
15                 break;
16             }
17         }
18         if(end==-1)
19             end=0;
20         return begin-end+1;
21     }
22 };

 

Leetcode(58)题解:Length of Last Word

原文:http://www.cnblogs.com/aezero/p/4709149.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!