AC Solution Java with trim() and split()


  • 5
    M
    public int countSegments(String s) {
        String trimmed = s.trim();
        if (trimmed.length() == 0) return 0;
        else return trimmed.split("\\s+").length;
    }

  • 0

    Sorry, what if there exists "," in the string? How do you fix it? Your code is accepted, but I don't know why this work. Can someone explain?


  • 0
    M

    @simplexp
    "Hello, my name is Minh"

    This String, when split will become "Hello,"; "my"; "name"; "is"; "Minh", has 5 sections. The "," will always attached to a String, so we don't really have to care about it.


  • 0

    Sorry again. I think I got it. We don't have to solve this problem. We use space to split the string so that comma is connected to one word which is not a independent element in the array.


  • 0

    @minhhoangtcu Hi, My name is Alex. That's right! Thank you. Sometimes when you don't see the outcome, it can a little tricky. 😁


  • 0
    I

    The test has been updated and this answer is actually wrong now because split("\s+") cannot split the space in the first position, like " , , sada"


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.