Go Leetcode: Crop N Length String
Problem
Given a string s
, return a cropped which max length is n
.
Also, spaces at prefix and postfix need to be removed.
Example 1:
1 | Input: "Hello World", 8 |
Example 2:
1 | Input: " Hello World ", 100 |
Example 3:
1 | Input: "Hello World", 3 |
Thought
Find the start point l
and end point r
then return result s[l:r]
Left point is easy to find. If s[l]
is space, pointer l
move right.
On the other hand, r
starts from l + N
, if s[r]
is NOT space, pointer r
move left.
The tricky point is that if the given string’s length equals to given n
,
and the string ends with character, the last word would be cropped.
Example:
1 | Input: "Learn Golang", 12 |
An easy solution is to append a SPACE to the given string at the beginning.
Code
1 | func crop(s string, n int) string { |