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

问题描述:

//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序列样本。我写了一个字符数的代码。有没有一种方法来优化这个C++代码(在时间,空间复杂度等方面)?

输出:

输入字符串:AGCTAGCATCGTGTCGCCCGTCTAGCATACGCATGATCGACTGTCAGCTAGTCAGACTAGTCGATCGATGTG

长度为72个字符。

性格:甲Occurence:16

性格:ģOccurence:19

字符:C Occurence:19

字符:T Occurence:18

+1

你试图解决什么问题? –

+0

到目前为止请显示您的研究/调试工作。请先阅读[问]页面。 –

+0

我的意思是如果它可以更快执行。 –

要存储都遇到字符并通过向量计数器动态调整它们的大小,并且每次遍历所有元素执行搜索。字符的总数是已知的(假设为256)。所以你可以将计数器声明为数组并通过char将它们索引。

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

不会将大小修改为256个字符会增加空间复杂度?我的意思是,如果不同的字符少,出现次数少。 –

+0

不,因为无论如何我们最终需要为矢量分配相同的256个字符(给定的输入字符串变化不够)。实际上,由于我们不再需要矢量,所以减少了空间复杂性。 – VTT

+0

@PlabanBiswas&VTT渐进空间复杂度不会改变任何方式。它保持不变。 (时间复杂度也不会改变,它仍然是线性的) – user2079303