简体   繁体   English

字符的链接列表-int indexOf(String)

[英]linked list of chars - int indexOf(String)

How would you approach creating the method int indexOf(String str) if creating your own StringBuilder class as a linked list of char 's. 如果创建自己的StringBuilder类作为char的链表,您将如何创建int indexOf(String str)方法。 Would you loop through with a bunch of logic or would it be easier to parse the StringBuilder object and then compare each one with str? 您将使用一堆逻辑进行遍历,还是解析StringBuilder对象然后将每个对象与str进行比较会更容易? I've made a few attempts but not having luck sorting out the logic in cases such as below: 我进行了一些尝试,但在以下情况下运气不好,没有弄清楚逻辑:

Ex. 例如 query: 查询:

b1 = new MyStringBuilder("who is whoing over in whoville");
String s1 = new String("who");
String s2 = new String("whoing");
String s3 = new String("whoville");
String s4 = new String("whoviller");
String s5 = new String("wacky");  

My Current Method: 我目前的方法:
I can get this to work in cases where its at the beginning or if its not found but identifying str in the middle of the string is not working. 如果在开头或找不到字符串但在字符串中间标识str无效,我可以使用它。

public int indexOf(String str)
    {
        int index =-1; //index at which str is first found in linked list string of chars
        int count = 0; //num of matches
        int firstI = -1;
        int sI=0; // dynamic counter variable to allow str.length and for loop to interact
        CNode currNode = firstC;
        for (int i = 0; i < length; i++)
        {
            if (currNode.data == str.charAt(sI))
            {
                if (count < 1)
                    firstI = i;
                count++;
            }

            if (count == 0 && (sI == str.length()-1))
                sI=0;

            if (count == str.length())
            {
                index = firstI;
                break;
            }

            if (count > 0 && currNode.data != str.charAt(sI))
            {
                sI = 0;
                count = 0;
            }


            currNode = currNode.next; //increment
            sI++;
        }

        return index;
    } 

Assuming MyStringBuilder has toString() , you could implement in terms of that. 假设MyStringBuilder具有toString() ,就可以实现这一点。

If you aren't allowed to do that, you need to do some looping through your list of chars to find the first char. 如果不允许这样做,则需要在字符列表中进行一些循环以找到第一个字符。 If that matches does the next char match the second in the word you are looking for and so on. 如果匹配,则下一个字符与您要查找的单词中的第二个字符匹配,依此类推。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM