Length of the last word of Code15

topic

leetcode58. The length of the last word
Given a string
s containing only uppercase and lowercase letters and spaces'' , return the length of the last word. If the string scrolls from left to right, then the last word is the last word that appears.
If there is no last word, please return 0.
Note: A word refers to the largest substring consisting only of letters and not containing any space characters.

Example:
Input: "Hello World"
Output: 5

Code

  • Ideas
    • Traverse backwards from the end, counting from the first non-space, until it encounters a space again or the traversal ends.
  • Code
// C
#include <string.h>
int lengthOfLastWord(char* s) {
    
    
  int len = 0;
  for (int i = strlen(s)-1; i >= 0; --i){
    
    
    if (s[i] != ' '){
    
    
      ++len;
    }else {
    
    
      if (len) {
    
    
        break;
      }
    } 
  }

  return len;
}

// C++
#include <string>
using namespace std;
class Solution {
    
    
 public:
  int lengthOfLastWord(string s) {
    
    
    int len = 0;
    for (int i = s.size() - 1; i >= 0; --i) {
    
    
      if (s[i] != ' ') {
    
    
        ++len;
      } else {
    
    
        if (len) {
    
    
          break;
        }
      }
    }
    return len;
  }
};

test

#include <iostream>
int main() {
    
    
  {
    
    
    char* s = "Hello World";
    cout << lengthOfLastWord(s) << endl;
  }
  {
    
    
    string s = "Hello World";
    Solution so;
    cout << so.lengthOfLastWord(s) << endl;
  }
  cin.get();
  return 0;
}
  • result:
5
5

Guess you like

Origin blog.csdn.net/luoshabugui/article/details/109655765