雖然這裏的許多答案都爲O(n^2),我嘗試使用遞歸O(n)的時間內做到這一點。這是從我已經有了,所以我知道該方法返回一個int現有代碼的修改,但我不使用它(它是從複製的代碼遺留下來的 - 修復它,你認爲合適)
public class CountCharSeqRecursive {
private String test = "AAABBA"; // (3)A(2)B(1)A
private StringBuilder runningString = new StringBuilder();
public static void main(String[] args) {
CountCharSeqRecursive t = new CountCharSeqRecursive();
System.out.println(t.getEncryptedValue(t.test));
}
public String getEncryptedValue(String seq){
int startIndex=0;
this.createCounterSeq(seq.charAt(startIndex), seq, startIndex);
return runningString.toString();
}
private int createCounterSeq(char prev, String sequence, int currentIndex){
return createCounterSeq(prev, sequence, currentIndex, 0);
}
private int createCounterSeq(char prev, String sequence, int currentIndex, int count){
if(currentIndex<sequence.length()){
char current = sequence.charAt(currentIndex);
if((prev^current) < 1){
++count;
}else {
this.addToSequence(count, prev);
count = 1;
}
return count += createCounterSeq(current, sequence, ++currentIndex, count);
}
this.addToSequence(count, prev);
return count;
}
private void addToSequence(int count, char ch){
runningString.append("("+count+")").append(ch);
}
}
來源
2013-11-20 16:48:52
Dan
這是一個調試器會在調試代碼有用) – 2013-03-25 12:13:13
可以請你建議我一些調試工具 – Abs 2013-03-25 12:37:54
大多數IDE都有一個調試器。它通常是Run旁邊的按鈕。我使用IntelliJ CE,但Eclipse和Netbeans也具有出色的調試器。 – 2013-03-25 13:03:35