1

我正在做一个java项目,它需要确定一个字符串是否包含另一个字符串,遵循以下逻辑:

  • 包含“isstr”的父字符串“这是一个父字符串”应该返回 true。因为“isstr”的所有字符都可以在父字符串保留子字符串顺序中找到。
  • 包含应该不区分大小写。

有没有人可以帮助我如何以简单有效的方式编写逻辑,或者任何库也非常感谢!

4

4 回答 4

1

可以说“这是父字符串”是您的父字符串。“isstr”是查询字符串。

对于不区分大小写的匹配,将父字符串和查询字符串都转换为小写。

您可以将父字符串拆分为关键字,并在查询字符串中查找每个关键字。

反转查询字符串(“isstr”)并将其压入堆栈,因为您想保留顺序。

Stack<Character> stack = new Stack<Character>();
String reversedQueryString = new StringBuilder(queryString).reverse().toString();
for (char ch: reversedQueryString.toCharArray()) {
    stack.push(ch);
}

从查询字符串中弹出字母,当它们匹配父字符串中的字母时。Stack 在这种情况下很有用,因为我们不关心是否再次找到相同的字符。

String[] keywords = parentString.split(" "); \\ to split on spaces.
for(String keyword : keywords){
    processKeyword(keyword);
}

void processKeyword(String keyword){
    for (char c: keyword.toCharArray()) {
        if(stack.top().equals(c)){
            stackCheck();
        }  
    } 
}

void stackCheck(){
    if(!stack.isEmpty())
       stack.pop();
    else{
       System.out.println("Eureka");

    }
}

这只是一个示例,您的实现可能会有所不同。例如,您可能希望检查关键字中的两个字符以相信其部分包含查询字符串。

于 2013-10-07T03:03:04.130 回答
1

它可以像这样简单:

public boolean contains(final String base, final String search){
    final String baseLowerCase = base.toLowerCase(Locale.ENGLISH);
    for(final char c : search.toLowerCase(Locale.ENGLISH).toCharArray())
        if(baseLowerCase.indexOf(c) < 0)
            return false;
    return true;
}

例如:contains("This is a parent string", "isstr");返回true

您在这里几乎要做的是将String您正在搜索的转换为您char[]将在其中迭代的。然后你想检查一下基地是否String包含char(使用String#indexOf(char))。您希望false在第一次出现时返回它不包含char(意思是String#indexOf(char)返回值 < 0)

于 2013-10-07T03:10:21.707 回答
0
public static void main(String[] args) {
    String parentStr = "This is a parent string", childStr = "iSStr";
    //Turn both to lowcase.
    parentStr.toLowerCase(); childStr.toLowerCase();
    Integer childStrIndex = 0;
    //Run over the parent string and if you found a match then keep comparing with the next
    //character in the child string.
    for (int index = 0 ; index < parentStr.length(); index++) {
        Character currChar = parentStr.charAt(index);
        if (childStr.length() <= childStrIndex)
            break;
        if (currChar.equals(childStr.charAt(childStrIndex)))
            childStrIndex++;
    }
    // If at the end you are in the last character of the child string, then is true.
    if (childStrIndex >= childStr.length())
        System.out.print(true);
    else
        System.out.print(false);
}

希望这可以帮助。顺便说一句,这听起来像家庭作业。

于 2013-10-07T03:10:44.390 回答
0

搜索将涉及回溯,因此如果您要手动实现它,则可能需要递归解决方案。

但一种简单的方法是将输入字符串预处理为正则表达式,然后执行正则表达式“查找”。例如,如果搜索字符串是“instr”,那么正则表达式可以是"[iI].*[nN].*[sS].*[tT].*[rR]".

请注意,此搜索不可避免地会很昂贵,如果使用正则表达式完成则更是如此。事实上,一个简单的实现是输入字符串O(M^N)的长度和搜索字符串的长度。MN

于 2013-10-07T03:38:05.130 回答