我有下類:(單鏈表)Java的算法
public class class CharNode {
private char _value;
private CharNode _next;
public CharNode(char val, CharNode n) {
_value = val;
_next = n;
}
public CharNode(char val) {
_value = val;
_next = null;
}
public int getValue() {
return _value;
}
public CharNode getNext() {
return _next;
}
public void setValue(char v) {
_value = v;
}
public void setNext(CharNode node) {
_next = node;
}
}
這個類:
public class CharList {
private CharNode _head;
public CharList()
{
_head = null;
}
//methods
}
我需要寫一個方法(叫「什麼」),其獲取兩個字符並返回以這些字符開始和結束的可能列表數量。 例如,如果鏈表「ABBCD」的方法是什麼(A,B)將返回2,什麼(A,C)將返回1的方法,我看到了一個解決方案:
public int what(char start, char end)
{
int count = 0, countStart = 0;
CharNode temp = _head;
while(temp != null)
{
if(temp.getValue() == start){
countStart++;
temp = temp.getNext();
if(temp.getValue() == start && start == end)
countStart++;
}
if(temp.getValue() == end && countStart>0){
count += countStart;
}
temp = temp.getNext();
}
return count;
}
但問題是我無法理解他們如何獲得算法。換句話說,它是如何工作的「數學」?
你試過調試那兩個測試用例嗎? – EasterBunnyBugSmasher
儘量寫你自己的。這樣,你需要考慮如何做到這一點。 – RealSkeptic
要點是:遍歷所有元素,如果找到與起始匹配的元素,則遍歷每個後續元素並計算匹配結束的元素。在我看來,它是以不必要的複雜和令人困惑的方式編寫的。我不會那樣寫。 – Michael