Regex, split and stack


  • 0
    T
    import java.util.regex.*;
    
    public class Solution {
        public boolean isValid(String code) {
            Pattern pattern = Pattern.compile("^/?([A-Z]{1,9})>(.*)");
            code = code.replaceAll("<!\\[CDATA\\[(.*?)]]>", ".");
            Stack<String> stack = new Stack<>();
            String[] str = code.split("<");
            if (str.length <= 2 || str[0].length() != 0) return false;
            for(int j = 1; j < str.length; j++) {
                if (j > 1 && stack.isEmpty()) return false;
                String s = str[j];
                Matcher matcher = pattern.matcher(s);
                
                if (!matcher.find()) return false;
                
                if (s.charAt(0) == '/') {
                    if (stack.isEmpty() || !stack.pop().equals(matcher.group(1))) return false;
                    if (j == str.length-1 && matcher.group(2).length() != 0) return false;
                } else {
                    stack.push(matcher.group(1));
                }
            }
            
            return stack.isEmpty();
        }
    }
    

Log in to reply
 

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