我必须在字符串中找到“连续的非空格字符序列”。 我的输出对于输入来说是错误的
Input=", , , , a, eaefa"
我的答案是 13 而不是 6。尽管我只计算了除空格之外的单词数。
class Solution {
public int countSegments(String s)
{
if(s.isEmpty()){
return 0;
}
else
{
int count=0;
String s1[]=s.split(" ");
for(int i=0;i<s1.length;i++)
{
if(s1[i]!=" ")
count++;
}
return count;
}
}
}
最佳答案
其他人建议使用:
s.split("\\s+").length
但是,有complications使用split
。具体来说,对于带有前导空格的字符串,上述内容将给出错误的答案。即使这些问题得到解决,它仍然过于昂贵,因为我们正在创建 count
个新字符串以及一个保存它们的数组。
我们可以通过迭代字符串并计算从非空格字符到空格字符或字符串末尾的次数来直接实现 countSegments
:
public static int countSegments(String s)
{
int count = 0;
for(int i=1; i<=s.length(); i++)
{
if((s.charAt(i-1) != ' ') && (i == s.length() || s.charAt(i) == ' ')) count++;
}
return count;
}
测试:
for(String s : new String[] {"", " ", "a", " a", "a ", " a ", ", , , , a, eaefa"})
System.out.format("<%s> : %d%n", s, countSegments(s));
输出:
<> : 0
< > : 0
<a> : 1
< a> : 1
<a > : 1
< a > : 1
<, , , , a, eaefa> : 6
关于java - "number of segments in a string"不适用于特定输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61577447/