返回介绍

solution / 0400-0499 / 0434.Number of Segments in a String / README_EN

发布于 2024-06-17 01:04:00 字数 3693 浏览 0 评论 0 收藏 0

434. Number of Segments in a String

中文文档

Description

Given a string s, return _the number of segments in the string_.

A segment is defined to be a contiguous sequence of non-space characters.

 

Example 1:

Input: s = "Hello, my name is John"
Output: 5
Explanation: The five segments are ["Hello,", "my", "name", "is", "John"]

Example 2:

Input: s = "Hello"
Output: 1

 

Constraints:

  • 0 <= s.length <= 300
  • s consists of lowercase and uppercase English letters, digits, or one of the following characters "!@#$%^&*()_+-=',.:".
  • The only space character in s is ' '.

Solutions

Solution 1

class Solution:
  def countSegments(self, s: str) -> int:
    return len(s.split())
class Solution {
  public int countSegments(String s) {
    int ans = 0;
    for (String t : s.split(" ")) {
      if (!"".equals(t)) {
        ++ans;
      }
    }
    return ans;
  }
}
class Solution {
public:
  int countSegments(string s) {
    int ans = 0;
    istringstream ss(s);
    while (ss >> s) ++ans;
    return ans;
  }
};
func countSegments(s string) int {
  ans := 0
  for _, t := range strings.Split(s, " ") {
    if len(t) > 0 {
      ans++
    }
  }
  return ans
}
class Solution {
  /**
   * @param String $s
   * @return Integer
   */
  function countSegments($s) {
    $arr = explode(' ', $s);
    $cnt = 0;
    for ($i = 0; $i < count($arr); $i++) {
      if (strlen($arr[$i]) != 0) {
        $cnt++;
      }
    }
    return $cnt;
  }
}

Solution 2

class Solution:
  def countSegments(self, s: str) -> int:
    ans = 0
    for i, c in enumerate(s):
      if c != ' ' and (i == 0 or s[i - 1] == ' '):
        ans += 1
    return ans
class Solution {
  public int countSegments(String s) {
    int ans = 0;
    for (int i = 0; i < s.length(); ++i) {
      if (s.charAt(i) != ' ' && (i == 0 || s.charAt(i - 1) == ' ')) {
        ++ans;
      }
    }
    return ans;
  }
}
class Solution {
public:
  int countSegments(string s) {
    int ans = 0;
    for (int i = 0; i < s.size(); ++i) {
      if (s[i] != ' ' && (i == 0 || s[i - 1] == ' ')) {
        ++ans;
      }
    }
    return ans;
  }
};
func countSegments(s string) int {
  ans := 0
  for i, c := range s {
    if c != ' ' && (i == 0 || s[i-1] == ' ') {
      ans++
    }
  }
  return ans
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文