【问题标题】:Is this a divide and conquer algorithm?这是一个分而治之的算法吗?
【发布时间】:2021-07-09 20:44:13
【问题描述】:

我正在为类做一个程序,给定一个字符串,获得由连续 {辅音,元音} 模式组成的最长子字符串,但我被要求以分而治之的方式进行。这是我的算法,但我不知道它是否是 D&V 算法。如果不是,我该如何修改它?

int cadenaMasLargaDeVC(string str) {
    int n = str.size();                    
    string strRes, strTmp = "";  
    int posRes = 0;
    set<char> st;
    st.insert('a');
    st.insert('e');
    st.insert('i');
    st.insert('o');
    st.insert('u');
    for(int i = 0; i<n; i++){
        cout << i << " ";
        if(st.find(str[i]) == st.end() && st.find(str[i+1]) != st.end()){
            strTmp += string(str[i]) + str[i+1];
            i++;
        } else{
            strTmp = "";
        }          
        if(strTmp.size() > strRes.size()){
            strRes = strTmp;
            posRes = i - strRes.size() + 2;
        }
        if(strRes.size() > (n-i)) break;
    }
    cout << strRes << endl;
    return posRes;
}

【问题讨论】:

    标签: c++ algorithm search data-structures divide-and-conquer


    【解决方案1】:

    不,分而治之范式通常具有以下精确步骤:

    1. 将较大的问题分解为较小的子问题。

    2. Conquer 有 Conquer 和 Combine 步骤,您可以在其中尝试解决无法进一步划分的基本(原子)问题并继续组合它们。

    在您提供的代码中,不涉及除法步骤。您只需要通过字符串中的两个连续字符并继续跟踪最长的时间,直到第 i 个位置。这类似于传递给定数组并保留 max 变量并在需要时对其进行更新。

    也许这个问题是为了划分并遍历所有两个长度的子字符串(原子问题),检查连续字符是否在询问的方式中,并在组合时适当地增加“计数”。

    【讨论】:

      猜你喜欢
      • 2019-05-16
      • 2013-01-12
      • 2013-02-02
      • 1970-01-01
      • 2012-01-01
      • 2011-12-31
      • 2013-02-03
      • 2017-06-08
      • 1970-01-01
      相关资源
      最近更新 更多