我写了一个字符数的代码。有没有办法优化这个C ++代码(在时间,空间复杂性等方面)?

时间:2017-04-18 05:03:41

标签: c++ string c++11 vector

//Code for Character Count
#include <iostream>
#include <string.h>
#include <vector>

std::vector <char> s_character;
std::vector <int>  count_occurence;


/*Function to check occurence of a character in the character vector,
if found return position,
else return -1 indicating no occurence
*/

int check_character_occurence(char character)
{
    for (int i=0;i<s_character.size();i++)
    {
        if(s_character.at(i)==character)
            return i;
    }    

    return -1;

}//end_of_check_character_occurence_function


/*Function to do the counting of individual characters,
if character is not present(occuring for the first time) then add to both character vector and count vector
else update count at position
*/

void count_algorithm(char character)
{
    int pos_flag;

    pos_flag = check_character_occurence(character);

    if (pos_flag==-1)
    {
        s_character.push_back(character);
        count_occurence.push_back(1);
    }

    else
        count_occurence.at(pos_flag)++;

}//end_of_count_algorithm_function


int main() 
{
    std::string  sequence;
    char separated_character;

    std::cout<<"\nEnter String: ";
    std::cin>>sequence;
    std::cout<<"\nLength is "<<sequence.length()<<" characters.";

    for(int i=0; i<sequence.length(); i++)
    {
        separated_character=sequence[i];
        count_algorithm(separated_character);
    } 

    for(int i=0;i < s_character.size(); i++)
        std::cout<<"\nCharacter: "<<s_character[i]<<" Occurence: "<<count_occurence[i];

    return 0;

}//end_of_main_code

为了测试,我采用了DNA序列样本。

输出:

输入字符串:AGCTAGCATCGTGTCGCCCGTCTAGCATACGCATGATCGACTGTCAGCTAGTCAGACTAGTCGATCGATGTG

长度为72个字符。

性格:一个出现:16

性格:G Occurence:19

性格:C出生时间:19

性格:T出生:18

1 个答案:

答案 0 :(得分:1)

您在向量中存储遇到的字符和计数器,动态调整它们的大小,并通过每次迭代所有元素来执行搜索。已知总字符数(假设为256)。因此,您可以将计数器声明为数组并使用char来索引它们。

std::array< int, 256 > counters{};
for(int i=0; i<sequence.length(); ++i)
{
    ++counters[sequence[i]];
}