“number of segments in a string” 对于特定输入不起作用。

huangapple go评论76阅读模式
英文:

"number of segments in a string" not working for a particular input

问题

我需要在一个字符串中找到“连续的非空字符序列”。
对于输入

Input=" , , , , a, eaefa";


我的输出是错误的,应该是6而不是13。尽管我只计算了除空格之外的单词。

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].equals(" "))
count++;
}
return count;
}
}
}

英文:

I have to find "contiguous sequence of non-space characters" in a string.
My output is coming wrong for the input

Input=&quot;, , , ,        a, eaefa&quot;

My answer is coming as 13 instead of 6.Though I have only counted words except for spaces.

class Solution {
    public int countSegments(String s) 
    {
        if(s.isEmpty()){
            return 0;
        }
        else
        {
            int count=0;
            String s1[]=s.split(&quot; &quot;);
            for(int i=0;i&lt;s1.length;i++)
            {
                if(s1[i]!=&quot; &quot;)
                    count++;
            }
            return count;
        }
    }
}

答案1

得分: 2

其他人建议使用:

s.split("\\s+").length

然而,使用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
英文:

Others have suggesting using:

s.split(&quot;\\s+&quot;).length

However, there are complications in using split. Specifically, the above will give incorrect answers for strings with leading spaces. Even if these issues are fixed it's still overly expensive as we're creating count new strings, and an array to hold them.

We can implement countSegments directly by iterating through the string and counting the number of times we go from a non-space character to a space character, or the end of the string:

public static int countSegments(String s)
{
	int count = 0;
	for(int i=1; i&lt;=s.length(); i++)
	{
		if((s.charAt(i-1) != &#39; &#39;) &amp;&amp; (i == s.length() || s.charAt(i) == &#39; &#39;)) count++;
	}
	return count;
}

Test:

for(String s : new String[] {&quot;&quot;, &quot; &quot;, &quot;a&quot;, &quot; a&quot;, &quot;a &quot;, &quot; a &quot;, &quot;, , , ,        a, eaefa&quot;})
	System.out.format(&quot;&lt;%s&gt; : %d%n&quot;, s, countSegments(s));

Output:

&lt;&gt; : 0
&lt; &gt; : 0
&lt;a&gt; : 1
&lt; a&gt; : 1
&lt;a &gt; : 1
&lt; a &gt; : 1
&lt;, , , ,        a, eaefa&gt; : 6

答案2

得分: 1

你应该在多个空格上使用 split,这样你就已经分割好了各个片段,所以你不需要编写 for 循环或其他内容。

// 由于 split 在处理前导空格时会出错,所以需要使用 trim
s = s.trim();
if (s.isEmpty()) return 0;
return s.split("\\s+").length;
  • 如果你只想匹配 字母数字 字符的序列,可以尝试使用这个正则表达式:"\\W+"
  • 如果你只想匹配 英文字母 的序列,你可以使用正则表达式 "[^A-Za-z]+"

在这里,它在多个空格上进行分割,而不仅仅是一个空格。

你当前的做法是,你计算了每一个非空格字符,而不是 "连续的非空格字符序列"。这就是为什么你得到的是 13 而不是 6。

注意,每当找到一个非空格字符时,计数就会增加,但如果你确实想要使用 for 循环来做到这一点,你应该有一个布尔标志,告诉你已经进入了一个序列,因此只有在该标志之前为假(你在序列外部时)并且然后找到一个空格时才增加计数。

另外,对于字符串比较,使用 != 是错误的,应该使用 equals 方法。

英文:

You should use split on multiple spaces, and then you have the segments already divided up for you, so you don't need to make a for-loop or anything.

//The trim is because split gets messed up with leading spaces, as SirRaffleBuffle said
s = s.trim();
if (s.isEmpty()) return 0;
return s.split(&quot;\\s+&quot;).length;
  • If you want only sequences of alphanumeric characters, you can try this regex instead: &quot;\\W+&quot;
  • If you want only sequences of English letters, you can do the same thing but with the regex &quot;[^A-Za-z]+&quot;.

Here, it splits on multiple spaces instead of just one.

The way you're currently doing it, you count every single letter that's not a whitespace instead of "contiguous sequences of no-space characters". That's why you're getting 13 instead of 6.

Notice that count is incremented anytime it finds something that isn't a space, but if you do want to do this with a for-loop, you should have a boolean flag telling you that you've entered a sequence, so you only increment count when that flat was previously false (you were outside a sequence) and then you find a space.

Also, using != for String comparison is wrong, you should use the equals method.

答案3

得分: 1

> “number of segments in a string” 无法处理特定输入

您可以通过使用正则表达式 \\s+ 来轻松实现:

public class Main {
    public static void main(String[] args) {
        String str = ", , , ,        a, eaefa";
        str = str.trim(); // 去除前导和尾随空格
        System.out.println(str.isEmpty() ? 0 : str.split("\\s+").length);
    }
}

输出:

6

正则表达式 \\s+ 匹配一个或多个连续的空格。

另外注意,您正在使用 != 来比较字符串,这是不正确的。请注意 ==!= 用于比较引用,而不是值。

英文:

> “number of segments in a string” not working for a particular input

You can do it easily by using the regex, \\s+ as follows:

public class Main {
	public static void main(String[] args) {
		String str = &quot;, , , ,        a, eaefa&quot;;
		str = str.trim();// Remove the leading and trailing space
		System.out.println(str.isEmpty() ? 0 : str.split(&quot;\\s+&quot;).length);
	}
}

Output:

6

The regex, \\s+ matches on one or more consecutive spaces.

On a side note, you are using != to compare strings, which is not correct. Note that == and != are used to compare the references, not the values.

huangapple
  • 本文由 发表于 2020年5月3日 23:55:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/61577447.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定