Share a short java solution


  • 14
    R

    Since there are just too many C++ and Python solutions here, I shared this solution in case someone need reference for Java.

    	public boolean isMatch(String s, String p) {
    		if (p.contains(".") || p.contains("*")) {
    			if (p.length() == 1 || p.charAt(1) != '*')
    				return comp(s, p, s.length(), 0) && isMatch(s.substring(1), p.substring(1));
    			for (int i = 0; i == 0 || comp(s, p, s.length(), i - 1); i++) {
    				if (isMatch(s.substring(i), p.substring(2)))
    					return true;
    			}
    		}
    		return s.equals(p);
    	}
    
    	private boolean comp(String s, String p, int sLen, int i) {
    		return sLen > i && (p.charAt(0) == s.charAt(i) || p.charAt(0) == '.');
    	}

  • 0
    J

    Actually we can just use String.matches(String)... It's accepted...

    Well, unless we want to "train" ourselves..


  • 0
    H

    Could you simply explain your code? It's quiet nice but a little hard for me to understand. Thank you.


  • 0
    D

    could you explain your code,sorry,i cann't understand it


Log in to reply
 

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