【发布时间】:2016-02-14 22:45:49
【问题描述】:
如果将您自己的StringBuilder 类创建为char 的链接列表,您将如何创建方法int indexOf(String str)。你会用一堆逻辑循环还是更容易解析StringBuilder对象然后将每个对象与str进行比较?我做了一些尝试,但在以下情况下没有运气整理出逻辑:
例如。查询:
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");
我目前的方法:
如果它在开头或者没有找到但在字符串中间识别 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;
}
【问题讨论】:
标签: java string linked-list indexof