如果你正在尋找一個良好的十六進制數字的方法:
boolean isHexDigit(char c) {
return Character.isDigit(c) || (Character.toUpperCase(c) >= 'A' && Character.toUpperCase(c) <= 'F');
}
提示或建議,根據要求:
個
- 所有遞歸方法調用自己與不同的輸入(當然,希望不同的輸入!)
- 所有遞歸方法有一個停止條件。
你的方法簽名應該是這個樣子
boolean isHexString(String s) {
// base case here - an if condition
// logic and recursion - a return value
}
而且,不要忘記,十六進制字符串可以以「0x」開始。這可能(更)難以做到,所以我會先讓常規函數工作。如果稍後解決它,請記住0xABCD0x123不應該通過。:-)
關於子:直從String類來源:
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > count) {
throw new StringIndexOutOfBoundsException(endIndex);
}
if (beginIndex > endIndex) {
throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
}
return ((beginIndex == 0) && (endIndex == count)) ? this :
new String(offset + beginIndex, endIndex - beginIndex, value);
}
偏移類型的成員變量int
值是類型的成員變量char[]
和它調用的構造函數是
String(int offset, int count, char value[]) {
this.value = value;
this.offset = offset;
this.count = count;
}
這顯然是一個O(1)方法,調用一個O(1)構造函數。它可以做到這一點,因爲字符串是不可變的。您不能更改字符串的值,只能創建一個新字符串。 (因爲它們是無關的解決方案,所以我們忽略了諸如反射和sun.misc.unsafe
之類的東西!)因爲它不能改變,所以你也不必擔心其他的線程會與它混淆,所以它可以像村莊一樣通過自行車。
你在正確的軌道上。查找String.substring,並考慮如何設置字符串中所有字符的遞歸檢查。 – sverre 2011-04-15 19:31:24
請發佈您的代碼,我們可以看到它有什麼問題。 – NateTheGreat 2011-04-15 19:32:39
@sverre我在uni中有類似的東西(我們都不是?),我的TA試圖告訴我我的方法很差,因爲它使用了'String.substring()'解釋它使我的方法'O(n^2)'。我和教授一起拿着它(用String類的源代碼來證明我的情況)。讓我們希望Joel的TA不是那麼天真! :-) – corsiKa 2011-04-15 19:35:16