Table of Contents
ExampleExample
method one
algorithm
Example
Output
in conclusion
Home Backend Development C++ Count of each lowercase character in each prefix of length 1 to N after performing the described operation

Count of each lowercase character in each prefix of length 1 to N after performing the described operation

Sep 15, 2023 am 09:05 AM
prefix count operation

Count of each lowercase character in each prefix of length 1 to N after performing the described operation

In this problem, we need to perform the given operation for each string prefix. Finally, we need to count the frequency of each character.

We can use a greedy algorithm to solve this problem. We need to take each prefix of length K and update its characters according to the given conditions. We can use map to calculate the frequency of characters in the final string.

Problem Statement - We are given a string tr containing N lowercase alphabetic characters. Additionally, we are given a mapping list, containing a total of 26 elements. Each element is mapped to lowercase characters based on its value. For example, mapping[0] maps to "a", mapping[1] maps to "b", and mapping[25] maps to "z". Additionally, the mapped array contains 1 or -1.

We need to do the following.

  • Get the maximum characters from the prefix of length K and get the mapping value from the 'mapping' array.

  • If the mapped value is 1, increase all prefix elements by 1.

  • If the mapped value is -1, decrement all prefix elements by 1.

Here, adding elements means ‘a’ −> ‘b’, ‘b’ −> ‘c’,… ‘z’ −> ‘a’.

Decreasing elements mean, ‘a’->‘z’, ‘b’->‘a’,…. ‘z’->‘y’.

We need to perform the above operation for each prefix of length 1

ExampleExample

enter

mapping = {-1, 1, 1, -1, 1, 1, -1, -1, -1, 1, 1, 1, -1, 1, -1, 1, -1, 1, -1, 1, 1, 1, -1, 1, 1, 1}, S = ‘progress’
Copy after login

Output

0 0 0 1 0 1 0 0 0 0 0 0 1 0 0 2 2 1 0 0 0 0 0 0 0 0
Copy after login
Copy after login

illustrate

  • In a prefix of length 1, the largest character is 'p', which maps to -1. Therefore, the updated string will be 'orogress'.

  • In a prefix of length 2, the maximum character is ‘r’ and the mapping is -1. Therefore, the updated string will be "nqogress".

  • In a prefix of length 3, the largest character is 'q', and the mapping value is 1. Therefore, the updated string is 'orpgress'.

  • When we are done with everything, the final string will be 'pqmfpdqr', which contains 1 'f', 2 'p', 2 'q', 1 'm', 1 'd' and 1 'd' 'r'. In the output, we print the frequency of each character in the resulting string.

enter

mapping = {-1, 1, 1, -1, 1, 1, -1, -1, -1, 1, 1, 1, -1, 1, -1, 1, -1, 1, -1, 1, 1, 1, -1, 1, 1, 1}, S = "ab", 
Copy after login

Output

1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Copy after login

Explanation− After performing all operations, the final string is 'ac' and we printed the frequency of each character.

method one

In this method, we will iterate through the string and take the value of K equal to the index P. After that, we will take the prefix with length equal to P, find the largest character, take the mapped value, and update all prefix characters accordingly.

algorithm

Step 1 − Define the ‘max_char’ variable to store the maximum character for the given prefix.

Step 2 − Similarly, initialize a list of length 26 with zeros in order to store the frequency of each character in the final string.

Step 3- Start looping through the string and initialize the "max_char" variable with 96 inside the loop.

Step 4 - Use nested loops to find the largest character from a prefix of length p.

Step 5 - Update each character of the prefix by adding the mapped value of max_char.

Step 7 - If the updated character is smaller than "a", update it to "z".

Step 8 - If the updated character is larger than "z", update it to "a".

Step 9− Finally, store the frequency of each character in a list by looping through the updated string.

Step 10- Print the frequency of characters.

Example

#include <bits/stdc++.h>
using namespace std;

void performOperations(string &str, vector<int> &mapping) {
    int len = str.length();
    char max_char;
    //  array to store the final frequency of each character
    int freq[26] = {0};
    for (int p = 0; p < len; p++) {
        max_char = 96;
        // Get the maximum character from the prefix string
        for (int q = 0; q <= p; q++) {
            max_char = max(max_char, str[q]);
        }
        // Update the prefix string by adding the max character's value.
        for (int q = 0; q <= p; q++) {
            // adding the mapping value to the current character
            str[q] += mapping[max_char - 'a'];
            // If the updated value is greater than z or less than a, update it
            if (str[q] < 'a') {
                str[q] = 'z';
            } else if (str[q] > 'z') {
                str[q] = 'a';
            }
        }
    }
    // Counting frequency of each character
    for (int p = 0; p < len; p++) {
        freq[str[p] - 'a']++;
    }
    // print count of each character in the updated string
    for (auto ch : freq) {
        cout << ch << ' ';
    }
}
int main() {
    string S = "progress";
    vector<int> mapping = {-1, 1, 1, -1, 1, 1, -1, -1,
                           -1, 1, 1, 1, -1, 1, -1, 1, -1,
                           1, -1, 1, 1, 1, -1, 1, 1, 1};
    performOperations(S, mapping);
    return 0;
}
Copy after login

Output

0 0 0 1 0 1 0 0 0 0 0 0 1 0 0 2 2 1 0 0 0 0 0 0 0 0
Copy after login
Copy after login

Time complexity− O(N*N) because we use two nested loops to traverse the string.

Space complexity− O(1), because we use constant space to store the frequency of characters.

in conclusion

We perform the given operation on the input string and print the character frequency of the updated string in the output. Programmers can also use maps in C to store character frequencies instead of using lists. For more practice, the programmer could try printing the cumulative frequency of each character in the updated string.

The above is the detailed content of Count of each lowercase character in each prefix of length 1 to N after performing the described operation. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

C language data structure: data representation and operation of trees and graphs C language data structure: data representation and operation of trees and graphs Apr 04, 2025 am 11:18 AM

C language data structure: The data representation of the tree and graph is a hierarchical data structure consisting of nodes. Each node contains a data element and a pointer to its child nodes. The binary tree is a special type of tree. Each node has at most two child nodes. The data represents structTreeNode{intdata;structTreeNode*left;structTreeNode*right;}; Operation creates a tree traversal tree (predecision, in-order, and later order) search tree insertion node deletes node graph is a collection of data structures, where elements are vertices, and they can be connected together through edges with right or unrighted data representing neighbors.

The truth behind the C language file operation problem The truth behind the C language file operation problem Apr 04, 2025 am 11:24 AM

The truth about file operation problems: file opening failed: insufficient permissions, wrong paths, and file occupied. Data writing failed: the buffer is full, the file is not writable, and the disk space is insufficient. Other FAQs: slow file traversal, incorrect text file encoding, and binary file reading errors.

How to calculate c-subscript 3 subscript 5 c-subscript 3 subscript 5 algorithm tutorial How to calculate c-subscript 3 subscript 5 c-subscript 3 subscript 5 algorithm tutorial Apr 03, 2025 pm 10:33 PM

The calculation of C35 is essentially combinatorial mathematics, representing the number of combinations selected from 3 of 5 elements. The calculation formula is C53 = 5! / (3! * 2!), which can be directly calculated by loops to improve efficiency and avoid overflow. In addition, understanding the nature of combinations and mastering efficient calculation methods is crucial to solving many problems in the fields of probability statistics, cryptography, algorithm design, etc.

What are the basic requirements for c language functions What are the basic requirements for c language functions Apr 03, 2025 pm 10:06 PM

C language functions are the basis for code modularization and program building. They consist of declarations (function headers) and definitions (function bodies). C language uses values ​​to pass parameters by default, but external variables can also be modified using address pass. Functions can have or have no return value, and the return value type must be consistent with the declaration. Function naming should be clear and easy to understand, using camel or underscore nomenclature. Follow the single responsibility principle and keep the function simplicity to improve maintainability and readability.

Function name definition in c language Function name definition in c language Apr 03, 2025 pm 10:03 PM

The C language function name definition includes: return value type, function name, parameter list and function body. Function names should be clear, concise and unified in style to avoid conflicts with keywords. Function names have scopes and can be used after declaration. Function pointers allow functions to be passed or assigned as arguments. Common errors include naming conflicts, mismatch of parameter types, and undeclared functions. Performance optimization focuses on function design and implementation, while clear and easy-to-read code is crucial.

Concept of c language function Concept of c language function Apr 03, 2025 pm 10:09 PM

C language functions are reusable code blocks. They receive input, perform operations, and return results, which modularly improves reusability and reduces complexity. The internal mechanism of the function includes parameter passing, function execution, and return values. The entire process involves optimization such as function inline. A good function is written following the principle of single responsibility, small number of parameters, naming specifications, and error handling. Pointers combined with functions can achieve more powerful functions, such as modifying external variable values. Function pointers pass functions as parameters or store addresses, and are used to implement dynamic calls to functions. Understanding function features and techniques is the key to writing efficient, maintainable, and easy to understand C programs.

distinct function usage distance function c usage tutorial distinct function usage distance function c usage tutorial Apr 03, 2025 pm 10:27 PM

std::unique removes adjacent duplicate elements in the container and moves them to the end, returning an iterator pointing to the first duplicate element. std::distance calculates the distance between two iterators, that is, the number of elements they point to. These two functions are useful for optimizing code and improving efficiency, but there are also some pitfalls to be paid attention to, such as: std::unique only deals with adjacent duplicate elements. std::distance is less efficient when dealing with non-random access iterators. By mastering these features and best practices, you can fully utilize the power of these two functions.

C language multithreaded programming: a beginner's guide and troubleshooting C language multithreaded programming: a beginner's guide and troubleshooting Apr 04, 2025 am 10:15 AM

C language multithreading programming guide: Creating threads: Use the pthread_create() function to specify thread ID, properties, and thread functions. Thread synchronization: Prevent data competition through mutexes, semaphores, and conditional variables. Practical case: Use multi-threading to calculate the Fibonacci number, assign tasks to multiple threads and synchronize the results. Troubleshooting: Solve problems such as program crashes, thread stop responses, and performance bottlenecks.

See all articles