Created
May 18, 2017 10:25
-
-
Save zhugw/4b2aadcae544734bc639eff918967d1e to your computer and use it in GitHub Desktop.
StringMatchPattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 面试题: | |
* *表示0或多个字符 判断一个字符串是否匹配模板 | |
* 如 字符串"abc"匹配"a*c" 字符串"abc"不匹配"a*d" | |
* Created by zhuguowei on 5/18/17. | |
*/ | |
public boolean match(final String s, final String pattern) { | |
if (s == null || pattern == null) { | |
throw new IllegalArgumentException("params cannot be null"); | |
} | |
if (pattern.equals("*")) { | |
return true; | |
} | |
if (pattern.indexOf("*") == -1) { // 不含通配符 直接比较 | |
return s.equals(pattern); | |
} | |
String[] split = pattern.split("\\*"); | |
boolean match = s.startsWith(split[0]); | |
if (!match) { | |
return match; | |
} | |
int fromIndex = split[0].length(); | |
for (int i = 1; i < split.length; i++) { | |
int index = s.indexOf(split[i], fromIndex); | |
if (index == -1) { | |
return false; | |
} | |
fromIndex = index + split[i].length(); | |
} | |
if (!pattern.endsWith("*")) { // 若不是以通配符结尾 尾部需要严格匹配 | |
match = s.endsWith(split[split.length - 1]); | |
} | |
return match; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment