📌  相关文章
📜  右上的按字典顺序排列的较小字符的计数

📅  最后修改于: 2021-04-23 15:30:58             🧑  作者: Mango

给定一个仅包含小写英文字母的字符串。任务是在每个索引的字符右侧计算按字母顺序排列的较小字符的总数。

例子:

天真的方法:
这个想法是要遍历字符串每个索引右侧的所有字符,并打印字母顺序较小的字符数。

C++
#include 
using namespace std;
  
// function to count the smaller
// characters at the right of index i
void countSmaller(string str)
{
  
    // store the length of string
    int n = str.length();
    for (int i = 0; i < n; i++) {
  
        // for each index initialize
        // count as zero
        int cnt = 0;
        for (int j = i + 1; j < n; j++) {
  
            // increment the count if
            // characters are smaller
            // than at ith index
            if (str[j] < str[i]) {
                cnt += 1;
            }
        }
  
        // print the count of characters
        // smaller than the index i
        cout << cnt << " ";
    }
}
  
// Driver code
int main()
{
    // input string
    string str = "edcba";
    countSmaller(str);
}


Java
class GFG
{
  
// function to count the smaller
// characters at the right of index i
static void countSmaller(String str)
{
  
    // store the length of String
    int n = str.length();
    for (int i = 0; i < n; i++) 
    {
  
        // for each index initialize
        // count as zero
        int cnt = 0;
        for (int j = i + 1; j < n; j++)
        {
  
            // increment the count if
            // characters are smaller
            // than at ith index
            if (str.charAt(j) < str.charAt(i))
            {
                cnt += 1;
            }
        }
  
        // print the count of characters
        // smaller than the index i
        System.out.print(cnt+ " ");
    }
}
  
// Driver code
public static void main(String[] args)
{
    // input String
    String str = "edcba";
    countSmaller(str);
}
}
  
// This code is contributed by 29AjayKumar


Python3
# function to count the smaller
# characters at the right of index i
def countSmaller(str):
  
    # store the length of String
    n = len(str);
    for i in range(n):
  
        # for each index initialize
        # count as zero
        cnt = 0;
        for j in range(i + 1, n):
  
            # increment the count if
            # characters are smaller
            # than at ith index
            if (str[j] < str[i]):
                cnt += 1;
              
        # print the count of characters
        # smaller than the index i
        print(cnt, end =" ");
      
# Driver code
if __name__ == '__main__':
  
    # input String
    str = "edcba";
    countSmaller(str);
  
# This code is contributed by PrinciRaj1992


C#
using System;
  
class GFG
{
  
// function to count the smaller
// characters at the right of index i
static void countSmaller(String str)
{
  
    // store the length of String
    int n = str.Length;
    for (int i = 0; i < n; i++) 
    {
  
        // for each index initialize
        // count as zero
        int cnt = 0;
        for (int j = i + 1; j < n; j++)
        {
  
            // increment the count if
            // characters are smaller
            // than at ith index
            if (str[j] < str[i])
            {
                cnt += 1;
            }
        }
  
        // print the count of characters
        // smaller than the index i
        Console.Write(cnt+ " ");
    }
}
  
// Driver code
public static void Main(String[] args)
{
    // input String
    String str = "edcba";
    countSmaller(str);
}
}
  
// This code is contributed by 29AjayKumar


C++
#include 
using namespace std;
  
// Function to count the smaller
// characters on the right of index i
void countSmaller(string str)
{
    // store the length of string
    int n = str.length();
  
    // initialize each elements of
    // arr to zero
    int arr[26] = { 0 };
  
    // array to store count of smaller characters on
    // the right side of that index
    int ans[n];
  
    for (int i = n - 1; i >= 0; i--) {
  
        arr[str[i] - 'a']++;
  
        // initialize the variable to store
        // the count of characters smaller
        // than that at index i
        int ct = 0;
  
        // adding the count of characters
        // smaller than index i
        for (int j = 0; j < str[i] - 'a'; j++) {
            ct += arr[j];
        }
        ans[i] = ct;
    }
  
    // print the count of characters smaller
    // than index i stored in ans array
    for (int i = 0; i < n; i++) {
        cout << ans[i] << " ";
    }
}
  
// Driver Code
int main()
{
    string str = "edcbaa";
    countSmaller(str);
  
    return 0;
}


Java
class GFG
{
  
// Function to count the smaller
// characters on the right of index i
static void countSmaller(String str)
{
    // store the length of String
    int n = str.length();
  
    // initialize each elements of
    // arr to zero
    int arr[] = new int[26];
  
    // array to store count of smaller characters on
    // the right side of that index
    int ans[] = new int[n];
  
    for (int i = n - 1; i >= 0; i--)
    {
  
        arr[str.charAt(i) - 'a']++;
  
        // initialize the variable to store
        // the count of characters smaller
        // than that at index i
        int ct = 0;
  
        // adding the count of characters
        // smaller than index i
        for (int j = 0; j < str.charAt(i) - 'a'; j++) 
        {
            ct += arr[j];
        }
        ans[i] = ct;
    }
  
    // print the count of characters smaller
    // than index i stored in ans array
    for (int i = 0; i < n; i++)
    {
        System.out.print(ans[i] + " ");
    }
}
  
// Driver Code
public static void main(String[] args)
{
    String str = "edcbaa";
    countSmaller(str);
}
}
  
// This code is contributed by 29AjayKumar


Python3
# Function to count the smaller
# characters on the right of index i
def countSmaller(str):
  
    # store the length of String
    n = len(str);
  
    # initialize each elements of
    # arr to zero
    arr = [0]*26;
  
    # array to store count of smaller characters on
    # the right side of that index
    ans = [0]*n;
  
    for i in range(n - 1, -1, -1):
  
        arr[ord(str[i] ) - ord('a')] += 1;
  
        # initialize the variable to store
        # the count of characters smaller
        # than that at index i
        ct = 0;
  
        # adding the count of characters
        # smaller than index i
        for j in range(ord(str[i] ) - ord('a')):
            ct += arr[j];
          
        ans[i] = ct;
      
    # print the count of characters smaller
    # than index i stored in ans array
    for i in range(n):
        print(ans[i], end = " ");
      
# Driver Code
if __name__ == '__main__':
    str = "edcbaa";
    countSmaller(str);
      
# This code is contributed by Rajput-Ji


C#
using System;
  
class GFG
{
  
// Function to count the smaller
// characters on the right of index i
static void countSmaller(String str)
{
    // store the length of String
    int n = str.Length;
  
    // initialize each elements of
    // arr to zero
    int []arr = new int[26];
  
    // array to store count of smaller characters on
    // the right side of that index
    int []ans = new int[n];
  
    for (int i = n - 1; i >= 0; i--)
    {
  
        arr[str[i] - 'a']++;
  
        // initialize the variable to store
        // the count of characters smaller
        // than that at index i
        int ct = 0;
  
        // adding the count of characters
        // smaller than index i
        for (int j = 0; j < str[i] - 'a'; j++) 
        {
            ct += arr[j];
        }
        ans[i] = ct;
    }
  
    // print the count of characters smaller
    // than index i stored in ans array
    for (int i = 0; i < n; i++)
    {
        Console.Write(ans[i] + " ");
    }
}
  
// Driver Code
public static void Main(String[] args)
{
    String str = "edcbaa";
    countSmaller(str);
}
}
  
// This code is contributed by 29AjayKumar


输出:
4 3 2 1 0

时间复杂度: O( N 2 ),其中N =字符串的长度
辅助空间: O(1)

更好的方法:想法是使用自我平衡BST。
可以使用自平衡二进制搜索树(AVL,红黑等)来获得O(N log N)时间复杂度的解决方案。我们可以扩充这些树,以便每个节点N都包含以N为根的子树的大小。我们在以下实现中使用了AVL树。
我们从右到左遍历字符串,并将所有元素一一插入到AVL树中。在AVL树中插入新密钥时,我们首先将密钥与root进行比较。如果键大于根,则它大于根左子树中的所有节点。因此,我们将左侧子树的大小添加到要插入的键的较小元素的数量中。我们对根下的所有节点递归地遵循相同的方法。
有关以上方法的实现,请参考本文。

时间复杂度: O( N * log N )
辅助空间: O( N )

高效方法:
想法是使用哈希技术,因为字符串仅包含小写字母。因此,在这里我们可以采用大小为26的数组,该数组用于将较小字符的数量存储在该索引的右侧。

从右边遍历数组,并继续更新哈希数组中的字符数。现在,要找到右边较小的字符数,我们每次都可以遍历大小为26的哈希数组以计算到目前为止遇到的较小字符。

C++

#include 
using namespace std;
  
// Function to count the smaller
// characters on the right of index i
void countSmaller(string str)
{
    // store the length of string
    int n = str.length();
  
    // initialize each elements of
    // arr to zero
    int arr[26] = { 0 };
  
    // array to store count of smaller characters on
    // the right side of that index
    int ans[n];
  
    for (int i = n - 1; i >= 0; i--) {
  
        arr[str[i] - 'a']++;
  
        // initialize the variable to store
        // the count of characters smaller
        // than that at index i
        int ct = 0;
  
        // adding the count of characters
        // smaller than index i
        for (int j = 0; j < str[i] - 'a'; j++) {
            ct += arr[j];
        }
        ans[i] = ct;
    }
  
    // print the count of characters smaller
    // than index i stored in ans array
    for (int i = 0; i < n; i++) {
        cout << ans[i] << " ";
    }
}
  
// Driver Code
int main()
{
    string str = "edcbaa";
    countSmaller(str);
  
    return 0;
}

Java

class GFG
{
  
// Function to count the smaller
// characters on the right of index i
static void countSmaller(String str)
{
    // store the length of String
    int n = str.length();
  
    // initialize each elements of
    // arr to zero
    int arr[] = new int[26];
  
    // array to store count of smaller characters on
    // the right side of that index
    int ans[] = new int[n];
  
    for (int i = n - 1; i >= 0; i--)
    {
  
        arr[str.charAt(i) - 'a']++;
  
        // initialize the variable to store
        // the count of characters smaller
        // than that at index i
        int ct = 0;
  
        // adding the count of characters
        // smaller than index i
        for (int j = 0; j < str.charAt(i) - 'a'; j++) 
        {
            ct += arr[j];
        }
        ans[i] = ct;
    }
  
    // print the count of characters smaller
    // than index i stored in ans array
    for (int i = 0; i < n; i++)
    {
        System.out.print(ans[i] + " ");
    }
}
  
// Driver Code
public static void main(String[] args)
{
    String str = "edcbaa";
    countSmaller(str);
}
}
  
// This code is contributed by 29AjayKumar

Python3

# Function to count the smaller
# characters on the right of index i
def countSmaller(str):
  
    # store the length of String
    n = len(str);
  
    # initialize each elements of
    # arr to zero
    arr = [0]*26;
  
    # array to store count of smaller characters on
    # the right side of that index
    ans = [0]*n;
  
    for i in range(n - 1, -1, -1):
  
        arr[ord(str[i] ) - ord('a')] += 1;
  
        # initialize the variable to store
        # the count of characters smaller
        # than that at index i
        ct = 0;
  
        # adding the count of characters
        # smaller than index i
        for j in range(ord(str[i] ) - ord('a')):
            ct += arr[j];
          
        ans[i] = ct;
      
    # print the count of characters smaller
    # than index i stored in ans array
    for i in range(n):
        print(ans[i], end = " ");
      
# Driver Code
if __name__ == '__main__':
    str = "edcbaa";
    countSmaller(str);
      
# This code is contributed by Rajput-Ji

C#

using System;
  
class GFG
{
  
// Function to count the smaller
// characters on the right of index i
static void countSmaller(String str)
{
    // store the length of String
    int n = str.Length;
  
    // initialize each elements of
    // arr to zero
    int []arr = new int[26];
  
    // array to store count of smaller characters on
    // the right side of that index
    int []ans = new int[n];
  
    for (int i = n - 1; i >= 0; i--)
    {
  
        arr[str[i] - 'a']++;
  
        // initialize the variable to store
        // the count of characters smaller
        // than that at index i
        int ct = 0;
  
        // adding the count of characters
        // smaller than index i
        for (int j = 0; j < str[i] - 'a'; j++) 
        {
            ct += arr[j];
        }
        ans[i] = ct;
    }
  
    // print the count of characters smaller
    // than index i stored in ans array
    for (int i = 0; i < n; i++)
    {
        Console.Write(ans[i] + " ");
    }
}
  
// Driver Code
public static void Main(String[] args)
{
    String str = "edcbaa";
    countSmaller(str);
}
}
  
// This code is contributed by 29AjayKumar
输出:
5 4 3 2 0 0

时间复杂度: O(N * 26)
辅助空间: O(N + 26)