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
.
Solution:
class Solution { public: int lengthOfLastWord(string s) { if(s.size() == 0) return 0; else { while(s.back() == ‘ ‘) s.pop_back(); if(s.find(‘ ‘) == -1) return s.size(); else { int len = 0; while(s.back() != ‘ ‘) { len++; s.pop_back(); } return len; } } } };
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
Solution:
class Solution { public: void reverse(string &s, int start, int end) { int sz = (end - start) / 2 + 1; for (int i = 0; i < sz; i++) { if (start + i != end - i) { char tmp = s[start + i]; s[start + i] = s[end - i]; s[end - i] = tmp; } } } void clearExtralSpace(string &s) { while (s.front() == ‘ ‘) { s.erase(0, 1); } while (s.back() == ‘ ‘) { s.pop_back(); } int spacePos = s.find(‘ ‘); while (spacePos != -1) { while (s[spacePos + 1] == ‘ ‘) { s.erase(spacePos + 1, 1); } spacePos = s.find(‘ ‘, spacePos + 1); } } void reverseWords(string &s) { clearExtralSpace(s); if (s.size() > 1) { int isSpaceExist = s.find(‘ ‘); if (isSpaceExist != -1) { int szS = s.size(); reverse(s, 0, s.size() - 1); int charPos = 0; int nextSpacePos = s.find(‘ ‘, charPos + 1); while (nextSpacePos != -1) { reverse(s, charPos, nextSpacePos - 1); charPos = nextSpacePos + 1; nextSpacePos = s.find(‘ ‘, charPos + 1); } reverse(s, charPos, s.size() - 1); } } } };
时间: 2024-10-13 18:56:44