返回介绍

solution / 0900-0999 / 0942.DI String Match / README_EN

发布于 2024-06-17 01:03:32 字数 3891 浏览 0 评论 0 收藏 0

942. DI String Match

中文文档

Description

A permutation perm of n + 1 integers of all the integers in the range [0, n] can be represented as a string s of length n where:

  • s[i] == 'I' if perm[i] < perm[i + 1], and
  • s[i] == 'D' if perm[i] > perm[i + 1].

Given a string s, reconstruct the permutation perm and return it. If there are multiple valid permutations perm, return any of them.

 

Example 1:

Input: s = "IDID"
Output: [0,4,1,3,2]

Example 2:

Input: s = "III"
Output: [0,1,2,3]

Example 3:

Input: s = "DDI"
Output: [3,2,0,1]

 

Constraints:

  • 1 <= s.length <= 105
  • s[i] is either 'I' or 'D'.

Solutions

Solution 1

class Solution:
  def diStringMatch(self, s: str) -> List[int]:
    n = len(s)
    low, high = 0, n
    ans = []
    for i in range(n):
      if s[i] == 'I':
        ans.append(low)
        low += 1
      else:
        ans.append(high)
        high -= 1
    ans.append(low)
    return ans
class Solution {
  public int[] diStringMatch(String s) {
    int n = s.length();
    int low = 0, high = n;
    int[] ans = new int[n + 1];
    for (int i = 0; i < n; i++) {
      if (s.charAt(i) == 'I') {
        ans[i] = low++;
      } else {
        ans[i] = high--;
      }
    }
    ans[n] = low;
    return ans;
  }
}
class Solution {
public:
  vector<int> diStringMatch(string s) {
    int n = s.size();
    int low = 0, high = n;
    vector<int> ans(n + 1);
    for (int i = 0; i < n; ++i) {
      if (s[i] == 'I') {
        ans[i] = low++;
      } else {
        ans[i] = high--;
      }
    }
    ans[n] = low;
    return ans;
  }
};
func diStringMatch(s string) []int {
  n := len(s)
  low, high := 0, n
  var ans []int
  for i := 0; i < n; i++ {
    if s[i] == 'I' {
      ans = append(ans, low)
      low++
    } else {
      ans = append(ans, high)
      high--
    }
  }
  ans = append(ans, low)
  return ans
}
function diStringMatch(s: string): number[] {
  const n = s.length;
  const res = new Array(n + 1);
  let low = 0;
  let high = n;
  for (let i = 0; i < n; i++) {
    if (s[i] === 'I') {
      res[i] = low++;
    } else {
      res[i] = high--;
    }
  }
  res[n] = low;
  return res;
}
impl Solution {
  pub fn di_string_match(s: String) -> Vec<i32> {
    let s = s.as_bytes();
    let n = s.len();
    let mut res = Vec::with_capacity(n + 1);
    let (mut low, mut high) = (-1, (n + 1) as i32);
    for i in 0..n {
      res.push(
        if s[i] == b'I' {
          low += 1;
          low
        } else {
          high -= 1;
          high
        }
      );
    }
    res.push(low + 1);
    res
  }
}

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

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

发布评论

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