给定两个字符串,如果第一个字符串按顺序包含第二个字符串的字符序列,则返回 true,但不一定彼此相邻。
例如,字符串:“我现在很饿,想吃东西”,子字符串:“mto”。句子中 o 在 t 之前的子串不算数,它们必须按顺序排列,但不一定紧挨着。
我不是真的在寻找代码,只是一般来说你会如何解决这个问题!
最佳答案
通常当你第一次遇到问题时,你应该先评估你自己会如何解决这个问题,然后再考虑你将如何对计算机进行编程来解决这个问题。
如果您尝试自己解决示例问题,您很可能会从第二个字符串中的第一个字符“m”开始,然后搜索该字符在字符串中的首次出现。在第 3 个索引位置找到“m”后,您将从第 4 个索引开始计算以查找子字符串中的下一个字母。您将继续评估,直到发生以下两种情况之一:
- 你找不到其中一封信。这意味着结果为
false
。 - 子字符串中的字母用完了。这意味着结果为
true
。
如果您了解如何自己解决问题,只需将解决方案分解为多个步骤即可。
你没有要求它,但万一它使它更清楚,这里有一个解决问题的简单方法:
public static boolean sub(String string, String substring) {
// Keep track of our position in the string.
int index = 0;
// Iterate through all of the characters in the substring.
for (char character : substring.toCharArray()) {
// Find the current character starting from the last character we stopped on.
index = string.indexOf(character, index);
// If the method returned -1, the character was not found, so the result is false.
if (index == -1)
return false;
}
// If we reach this point, that means all characters were found, so the result is true.
return true;
}
关于java - 检查字符串是否按顺序包含子字符串的字符序列,但不一定彼此相邻,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30771362/