【发布时间】:2015-09-18 19:53:08
【问题描述】:
我的方法longestHorizontalSequence(Arraylist> myBoard) 应该返回具有相同元素的最长水平对象序列。如果myBoard 如下所示:
| 0| 1| 2| 3| 4| 5|
+---+---+---+---+---+---+
0 | ~| x| x| x| x| x|
+---+---+---+---+---+---+
1 | o| o| o| o| o| o|
+---+---+---+---+---+---+
2 | b| b| b| ~| ~| ~|
+---+---+---+---+---+---+
3 | ~| ~| ~| ~| ~| ~|
+---+---+---+---+---+---+
它应该返回我[[(1,0,o), (1,1,o), (1,2,o), (1,3,o), (1,4,o), (1,5,o)],并且该方法不计算this.element,即~。但相反,我的方法给了我[],当我调试时它给了我:
[(1,0,o), (1,1,o), (1,2,o), (1,2,o), (1,3,o), (1,3,o), (1,4,o), (1,4,o)] 第二行。错误在我的if loop 中,我不知道如何修复该错误。如果 smb 可以在这里帮助我,我将不胜感激。谢谢!
public List<RowColElem<T>> longestHorizontalSequence(Arraylist<ArrayList<T>> myBoard){
ArrayList<RowColElem<T>> result = new ArrayList<RowColElem<T>>();
int count = 1;
int max = 1;
// int elemCount = 1;
for(int i = 0; i < myBoard.size(); i++){
List<RowColElem<T>> currentList = new ArrayList<RowColElem<T>>();
RowColElem<T> obj = new RowColElem<T>(i, 0, myBoard.get(i).get(0));
T elem = obj.getElem();
// currentList.add(obj);
for(int j = 1; j < myBoard.get(i).size() - 1; j++){
currentList.add(obj);
if(elem.equals(myBoard.get(i).get(j))
&& (!(elem.equals(this.element)))
&& (!(myBoard.get(i).get(j).equals(this.element)))){
count++;
RowColElem<T> obj1 = new RowColElem<T>(i,j, myBoard.get(i).get(j));
currentList.add(obj1);
obj = new RowColElem<T>(i, j+1, myBoard.get(i).get(j));
elem = obj.getElem();
}
else{
elem = myBoard.get(i).get(j);
obj = new RowColElem<T>(i, j, myBoard.get(i).get(j));
while(count > 0){
currentList.remove(0);
count--;
}
if(count > max){
max = count;
}
else if(result.size() < currentList.size()){
result.clear();
result.addAll(currentList);
}
count = 1;
}
}
}
return result;
}
类RowColElem
public class RowColElem<T>{
private int row;
private int col;
private T e;
// Create a RowColElem with the parameter parts
public RowColElem(int r, int c, T e){
this.row = r;
this.col = c;
this.e = e;
}
// Return the row
public int getRow(){
return this.row;
}
// Return the column
public int getCol(){
return this.col;
}
// Return the element
public T getElem(){
return this.e;
}
// Return a pretty string version of the triple formated as
// (row,col,elem)
public String toString(){
String result = "";
if(this.e instanceof String){
String element = (String)this.e;
result = "(" + this.row + "," + this.col + "," + element + ")";
}
else if(this.e instanceof Integer){
Integer element = (Integer)this.e;
result = "(" + this.row + "," + this.col + "," + element + ")";
}
else if(this.e instanceof Character){
Character element = (Character)this.e;
result = "(" + this.row + "," + this.col + "," + element + ")";
}
return result;
}
}
【问题讨论】: