Skip to content

Instantly share code, notes, and snippets.

@ceth-x86
Created January 9, 2021 05:00
Show Gist options
  • Select an option

  • Save ceth-x86/9f5b3d49b9a9732eb3506797688d05e8 to your computer and use it in GitHub Desktop.

Select an option

Save ceth-x86/9f5b3d49b9a9732eb3506797688d05e8 to your computer and use it in GitHub Desktop.

Revisions

  1. ceth-x86 created this gist Jan 9, 2021.
    12 changes: 12 additions & 0 deletions another_cpp
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,12 @@
    class Solution {
    public:
    int lengthOfLastWord(string s) {
    int len = 0, tail = s.length() - 1;
    while (tail >= 0 && s[tail] == ' ') tail--;
    while (tail >= 0 && s[tail] != ' ') {
    len++;
    tail--;
    }
    return len;
    }
    };
    22 changes: 22 additions & 0 deletions cpp
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,22 @@
    class Solution {
    public:
    int lengthOfLastWord(string s) {
    int result = 0; int prev = 0;
    for (size_t i = 0; i < s.size(); i++) {
    if (s[i] != ' ') {
    result += 1;
    } else {
    if (result != 0) {
    prev = result;
    }
    result = 0;
    }
    }

    if (result != 0) {
    return result;
    } else {
    return prev;
    }
    }
    };
    13 changes: 13 additions & 0 deletions py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,13 @@
    class Solution:
    def lengthOfLastWord(self, s: str) -> int:
    result = 0; prev = 0
    for ch in s:
    if ch != ' ':
    result += 1
    else:
    if result != 0:
    prev = result
    result = 0

    return result if result != 0 else prev