我的项目是以递归方式计算char数组中的单词数。
push (location: RawLocation, onComplete?: Function, onAbort?: Function) {
this.history.push(location, onComplete, onAbort)
}
我有两个先前的方法来获取char []中的第一个空格:trimLeadingSpaces(char [] array)(返回一个char [];例如,我们有一个char [],如[abc],它返回[abc] ])和另一个知道第一个'的第一个索引的函数。 ':idxFirstSpace(char [] array,int currentIdx)并返回一个int。 我的问题在于方法countWords()。
//Code:
public static int countWords(char[] array) {
if (array == null)
throw new IllegalArgumentException("The received array is null");
char[] array_new = trimLeadingSpaces(array);
//Arrays.copyOfRange(array_new, idxFirstSpace(array_new, 0), array_new.length);
if(idxFirstSpace(array_new, 0) == 0)
return 0;
if(idxFirstSpace(array_new, 0) == array_new.length)
return 1;
return 0;
}
}
控制台:
// test method coundWords
test_coundWords("abc"); // = 1
test_coundWords(" abc "); // = 1
test_coundWords(" abc def"); // = 2
test_coundWords(" abc def d"); // = 3
test_coundWords("a a def d g "); // = 5
test_coundWords(" "); // = 0
test_coundWords(""); // = 0
test_coundWords(null); // = Erro: The received array is null
我可以更改方法并将char []更改为字符串。它必须只适用于char数组。
答案 0 :(得分:0)
我不会在这里使用递归,而是在保持少量状态的同时迭代字符数组:
true
这里的基本思想是我们记录何时击中空格字符,当发生这种情况时,我们在点击单词的开头(即单个非空格字符)时将计数增加1。请注意,此空格标志开始设置为{{1}},因为数组中的第一个字符可能是单词的开头。
答案 1 :(得分:0)
如果您对递归解决方案感兴趣(我们不谈论性能),那么您的代码几乎是正确的。这是修改后的例子:
public static int countWords(char[] array) {
if (array == null)
throw new IllegalArgumentException("The received array is null");
char[] array_new = trimLeadingSpaces(array);
if (array_new.length == 0)
return 0;
int nextSpacePosition = idxFirstSpace(array_new, 0);
int count = 1;
if (nextSpacePosition > 0 && nextSpacePosition < array_new.length)
count += countWords(Arrays.copyOfRange(array_new, nextSpacePosition, array_new.length));
return count;
}
P.S。 为了绝对清楚,我使用了trimLeadingSpaces()
和idxFirstSpace()
的以下实现:
private static char[] trimLeadingSpaces(char[] arr) {
String str = new String(arr);
while (str.length() > 0 && str.charAt(0) == ' ')
str = str.substring(1);
return str.toCharArray();
}
private static int idxFirstSpace(char[] arr, int currentIdx) {
return new String(arr).indexOf(' ', currentIdx);
}
答案 2 :(得分:0)
您的问题是在array.length
使用return 1 + countWords(Arrays.copyOfRange(array_new, idxFirstSpace(array_new, 0), array.length - 1));
输入" abc "
array_new
最终的长度为0,但array
的长度仍然为2(因为传递了2个空格的数组)。因此,将根据\0
上的JavaDoc添加终结符Arrays.copyOfRange()
:
范围(to)的最终索引(必须大于或等于from)可能大于original.length,在这种情况下,&#39; \ u000&#39;放置在索引大于或等于original.length - from的副本的所有元素中。
因此,您将新数组['\0']
视为另一个单词。将array.length
更改为array_new.length
,应该没问题。
请注意,在使用字符串时不应该发生这种情况,或者在使用调试器单步执行代码时至少应该弹出(对于有问题的输入,您输入countWords()
3次而不是2次只)。