A Way to Solve Without Regex Expression


  • 0
    N

    Construct a string abbr_s according to the abbr, then do the comparison.

    public class Solution {
        public boolean validWordAbbreviation(String word, String abbr) {
            StringBuilder abbr_s = new StringBuilder();
            char[] abbr_c = abbr.toCharArray();
            int buf = 0; // to read in a number
            
            for(char a : abbr_c)
            {
                int num = a - '0';
                if(Character.isDigit(a) && ((buf != 0 && num == 0) || num != 0))
                {
                    buf *= 10;
                    buf += num;
                }
                else
                {
                    if(buf != 0) //do the filling here
                    {
                        for(int i = 0; i < buf; i++)
                            abbr_s.append("*");
                    }
                    buf = 0;
                    abbr_s.append(a);
                }
            }
            
            if(buf != 0) //do the filling here
            {
                for(int i = 0; i < buf; i++)
                    abbr_s.append("*");
            }
            
            if(word.length() != abbr_s.toString().length()) return false;
            for(int i = 0; i < word.length(); i++)
            {
                if(abbr_s.toString().charAt(i) == '*')  continue;
                if(abbr_s.toString().charAt(i) != word.charAt(i))   return false;
            }
            
            return true;
        }
    }
    

Log in to reply
 

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