JAVA Regular expression solution


  • 0
    Y

    Regular expression is a powerful to to handle string problems. It is not necessary to use this method for this simple problem, and also this solution runs much slower than just go through the string in this question (9ms vs 0ms). I believe it is always good to learn different methods to solve one question, thus I put my code here for reference.

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class Solution2 {
        public int lengthOfLastWordRegex(String s) {
            if (s == null || s.length() == 0) return 0;
    
            // Reverse string so as to find the last word
            String reverseString = new StringBuilder(s).reverse().toString();
            Pattern r = Pattern.compile("(\\S+)");
            Matcher m = r.matcher(reverseString);
        
            if (m.find()) return m.group().length();
            else return 0;
        }
    }

Log in to reply
 

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