[英]Does String.split(" ") in Java do all the work up front?
Say I have a very long String called str
, and I'm looking for the first instance of "hello"
.假设我有一个很长的 String 叫做str
,我正在寻找"hello"
的第一个实例。 For now we can say each token is separated by a space, but in the more complex case it won't be, hence the use of split rather than StringTokenizer.现在我们可以说每个标记由一个空格分隔,但在更复杂的情况下它不会,因此使用 split 而不是 StringTokenizer。 Now, let's also say "hello"
is only the third word in the String.现在,让我们也说"hello"
只是字符串中的第三个单词。 Is the following algorithm O(n)
or O(1)
?以下算法是O(n)
还是O(1)
?
for (String word : str.split(" ") )
if ( word.equals("hello") ) return;
It would be O(1)
if it does not matter how many tokens you have in your array, which is not true.如果数组中有多少令牌并不重要,那将是O(1)
,这是不正确的。 It is O(n)
.它是O(n)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.