Skip to content

Commit

Permalink
Create: 0058-length-of-last-word.rb (neetcode-gh#2018)
Browse files Browse the repository at this point in the history
* Create 0058-length-of-last-word.rb

Two solutions:
- Simple one line solution
- Double pointer solution

* Update 0058-length-of-last-word.rb

Strip not needed in the one liner!

* Don't need to pass blank string arg to split

Even more simpler!
  • Loading branch information
MikeQCarr authored Jan 16, 2023
1 parent 7285c80 commit 3dd039d
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions ruby/0058-length-of-last-word.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# @param {String} s
# @return {Integer}

#simple one liner
def length_of_last_word(s)
s.split.last.length
end

#double pointer
def length_of_last_word(s)
left = -1
while s[left] == ' ' do
left -= 1
end

right = left
while s[left] && s[left] != ' ' do
left -=1
end

right - left
end

0 comments on commit 3dd039d

Please sign in to comment.