Pergunta de entrevista da empresa Google

Implement a method that matches an entire string with star wildcard pattern, e.g. returns true for ("*ogle", "Google"), but false for ("fragile*", "agile") - without using regular expression language support.

Respostas da entrevista

Sigiloso

16 de set. de 2011

Following code should resolve the problem: Consider that there can be only one '*' symbol in first pattern string boolean match (String a, String b) { boolean match = true; if(!a.contains("*")) { return a.equals(b); } else { String prefix = a.substring(0, a.indexOf('*')); String suffix = a.substring(a.indexOf('*')+1); if (StringUtils.isNotEmpty(prefix) && !b.startsWith(prefix)) { match = false; } if (StringUtils.isNotEmpty(suffix) && !b.endsWith(suffix)) { match = false; } } return match; } none of used class String methods use regular expression language support

Sigiloso

2 de mai. de 2013

Solution for any number of "*" in pattern: public boolean match(String str, String pattern) { if (str == null || pattern == null) return false; if (pattern.isEmpty() || pattern == "*") return true; int j = 0; for (int i = 0; i < str.length(); i++) { if (pattern.charAt(j) == '*') { if (match(str.substring(i + 1), pattern.substring(j + 1))) return true; } else if (pattern.charAt(j) == str.charAt(i)) { j++; } if (j == pattern.length()) return true; } return false; }