【发布时间】:2014-05-18 00:55:16
【问题描述】:
我正在尝试创建一种算法来确定一个数组列表 (s1) 是否是另一个数组列表 (s2) 的子序列。第一个列表中的元素都需要在第二个列表中,并且顺序必须相同。所以 s1 是 s2 的子序列,但 s1 不是 s2 的子序列。我需要使用迭代器来遍历每个列表,并且我应该只遍历每个列表一次(因为它必须按照相同的顺序)。我似乎对 next() 变得无效有疑问?什么会导致这个/我该如何解决这个问题? 我目前拥有的代码似乎可以正常工作,但不会转到第一个数组列表中的下一个元素。
import dataStructures.*;
public class Subsequence2
{
public static void main(String[] args)
{
ArrayList<Character> s1 = new ArrayList<Character>();
s1.add('n');
s1.add('p');
s1.add('a');
ArrayList<Character> s2 = new ArrayList<Character>();
s2.add('a');
s2.add('n');
s2.add('b');
s2.add('p');
s2.add('c');
s2.add('a');
Subsequence2 one = new Subsequence2();
System.out.print("S1 is a subsequence of S2 is a ");
System.out.print(one.subSequence(s1, s2));
System.out.print(" statment.");
} //end main
public static <T> boolean subSequence(ArrayList<T> s1, ArrayList<T> s2)
{
//if s1 is empty or if s1 and s2 are empty it is a subsequence
if(s1.isEmpty() || (s1.isEmpty() && s2.isEmpty()))
{
return true;
}
//if s2 is empty and s1 is not is is not a subsequence.
else if(s2.isEmpty())
{
return false;
}
else
{
int s1Count = 0; //count items matched
Iterator<T> itr1 = s1.iterator();
Iterator<T> itr2 = s2.iterator();
while(itr1.hasNext())
//for(Iterator<T> itr1 = s1.iterator(); itr1.hasNext();) //traverse s1
{
T c1 = itr1.getCurrent();
itr1.next(); //go to next element of s1
while(itr2.hasNext()) //traverse s2
{
T c2 = itr2.getCurrent();
//if items are equal check the next item and add 1 to count of items matched
if(c1.equals(c2))
{
itr2.next();
++s1Count;
//used for testing- just want to see what index it is pulling
System.out.print("s1 index " + s1.indexOf(c1) + " s2 index " + s2.indexOf(c2) + " \n" + c1 + " " + c2 + "\n");
}
//if it didn't match, check next element
else
{
itr2.next();
}
if(s1Count == s1.size()) //if match count is == to s1 size, it is a subsequence
{
return true;
}
} // end itr2 while
} //end for itr1
} //end else not empty
return false;
} //end subSequence method
}//end class
【问题讨论】:
-
我认为您使用 while(itr2.hasNext()) 的方式有误。这个循环将一直持续到结束,而外循环不会进入下一次迭代。
-
我还没有仔细看,但请注意
if(s1.isEmpty() || (s1.isEmpty() && s2.isEmpty())仅相当于if(s1.isEmpty())。如果s1为空,则整个条件短路到true(甚至没有评估|| (s1.isEmpty() & s2.isEmpty())位)。如果s1不为空,则将评估第二部分,但始终评估为false,因为它本质上是(false && s2.isEmpty())(因为我们知道s1.isEmpty()是假的)。 -
"所以 s1 是 s2 的子序列,但 s1 不是 s2 的子序列。" ?我没有得到这个......是我还是它自相矛盾?
-
@yshavit - 为什么我需要重新打开 s1 迭代器才能从头开始比较?我不想重复一遍
-
@yshavit - 这绝对是一个子序列。 Karen 真的不想打开一个新的 s1 迭代器。
标签: java algorithm arraylist iterator