Skip to content

Instantly share code, notes, and snippets.

@codethereforam
Last active March 20, 2019 06:18
Show Gist options
  • Save codethereforam/5f433bbe6f745aa9b5e6c5b56aeb0430 to your computer and use it in GitHub Desktop.
Save codethereforam/5f433bbe6f745aa9b5e6c5b56aeb0430 to your computer and use it in GitHub Desktop.
父字符串顺序匹配子字符串
/**
* String Utility
*
* @author yanganyu
* @date 2019/3/18 14:31
*/
public class StringUtil {
private StringUtil() {
}
/**
* 父字符串顺序匹配子字符串
* <pre>
* 子字符串只要按顺序出现在父字符串中就能匹配,中间缺几个字符不影响匹配
* 例子:
* inOrderMatches("abcdefg", "cfg") is true
* inOrderMatches("abcdefg", "ad") is true
* inOrderMatches("abcdefg", "acg") is true
* inOrderMatches("abcdefg", "efc") is false
* </pre>
*
* @param parentStr parentStr 父字符串
* @param childStr childStr 子字符串
* @return boolean
* @author yanganyu
* @date 2019/3/18 14:19
*/
public static boolean inOrderMatches(String parentStr, String childStr) {
if (parentStr == null || childStr == null) {
return false;
}
char[] parentChars = parentStr.toCharArray();
char[] childChars = childStr.toCharArray();
int parentCharsPos = 0;
for (int i = 0; i < childChars.length; i++) {
boolean flag = false;
for (; parentCharsPos < parentChars.length; parentCharsPos++) {
flag = childChars[i] == parentChars[parentCharsPos];
if (flag) {
parentCharsPos = parentCharsPos + 1;
break;
}
}
// parentChars遍历完
if (parentCharsPos == parentChars.length) {
// childChars没遍历判断完
if (i < childChars.length - 1) {
return false;
} else {
return flag;
}
}
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment