使用堆栈

时间:2018-03-29 13:25:27

标签: c++

我正在编写一个C ++函数,它实现一个堆栈来测试一个单词是否在语言L = {a ^ n-1b ^ n}中。存在的词包括b,abb,aabbb。

我已经看过许多关于用L = {a ^ nb ^ n}的语言测试单词的帖子,而我只是想知道当n不相等时如何解决这个问题。

我写的代码有效,但我觉得我正在采取简单的方法来确保这个单词的格式不像aba bababa abababa等。我已经在堆栈之外实现了这个测试但感觉应该有一种方法在堆栈中执行它。

我说这个的原因是因为我后来必须使用函数bool isInLanguageL(string w)并使用以下头文件而不是bool isInLanguageL(queueType& w)。我一直在尝试将以前使用字符串w的代码转换为队列w时遇到问题。

    //function prototype
    bool isInLanguageL(string w);

    //function to see if the word exists in the language
    bool isInLanguageL(string w) {

    //creating counters for the a's and b's 
    int countPush = 0;
    int countPop = 0;

    reverse(w.begin(), w.end()); //putting the b's infront  

    //creating the charachter stack
    stack<char> charStack;

    //checking the word for an illegal format such as aba or bab
    for (int i = 0; i < w.length(); i++) {

        if ((w[i] == 'a' && w[i + 1] == 'b' && w[i+2] == 'a') || (w[i] == 'b' && w[i + 1] == 'a' && w[i + 2] == 'b')) {

        cout << "This is an illegal format of a word in language L and therefore: ";
        return false;
        }

        else { //if the word is a legal format then continue onto stack creation

        //adding the b's to the stack and counting them simultaneously
        if (w[i] == 'b') {

            charStack.push(w[i]);
            countPush++;
        }

        //popping off the stack everytime there is an a and counting simultaneously
        else if (w[i] == 'a') {

            charStack.pop();
            countPop++;
        }
     }
  } 

    //if the stack is not empty and a = b-1 then the word exists
    if (!charStack.empty() && countPop == (countPush - 1))
        return true;
    else
        return false;
}

int main() {

//introduction
cout << "The language rule is L = {a^n-1b^n}" << endl;

//creating an empty string for the word and condition variable for exit
string word = " ";
int exit = 0;

while (exit == 0) {

    //getting word from the user
    cout << "\nWord: ";
    cin >> word;

    //calling function to check if word exists in L
    if (isInLanguageL(word)) {

        cout << "The word exists in language L" << endl << endl;
    }

    else
        cout << "The word doesn't exist in language L" << endl << endl;;

    cout << "Would you like to exit (1-yes/0-no): ";
    cin >> exit;
  } 

    system("pause");
    return 0;
}

如果有人能够指导我正确的方向测试这个词是否属于合法格式(不是aba abababa bababa),我们将不胜感激。

0 个答案:

没有答案