如何比较字符串以查看在"$"之前输入的字符是否等于它之后的字符?

How to Compare a string to see if the characters entered before '$' are equal to the ones after it?

本文关键字:字符 何比较 输入 是否 之后 于它 字符串 比较      更新时间:2023-10-16

我一直在为一本书实现一个算法,如下所示:

L={w$w':w可能是一个空字符串,而不是$w'=reverse(w)}

根据书中的伪代码,我为我的程序编写了代码,该代码将使用您输入的字符串,例如(a$a,ABC$CBA),并比较$前后的字符,以确定它们是否是回文。我完全按照书中的指示编写了代码,但程序运行不正常。无论我输入什么,它总是返回false。

我不知道我做错了什么。

这是我写的代码:

#include <iostream>
#include "stack.h"
#include <string>
using namespace std;
bool isInLanguage(string aString)
{
  Stack<char> aStack;
  int i = 0;
  // ch is aString[i]
  while( aString[i] != '$')
  {
      aStack.push(aString[i]);
      ++i;
  }
  //skip the $
  ++i;
  //match the reverse of w
  bool inLanguage = true; // assume string is in language
  while(inLanguage && i < aString.length())
  {
      char stackTop;
      aStack.pop(stackTop);
      if(stackTop == aString[i])
          ++i; //characters match
      else
          //top of stack is not aString[i]
          inLanguage = false; //reject string
      if(aStack.isEmpty())
  {
      //pop failed, stack is empty. first half of string
      //is shorter than second half)
      inLanguage = false;
  } // end if
  } // end while
   if (inLanguage && aStack.isEmpty())
          return true;
      else
          return false;
} // end isInLanguage
int main()
{
    string str;
    bool boolean;
    cout << "Enter a string to be checked by the algorithm : ";
    cin >> str;
    boolean = isInLanguage(str);
    if (boolean == true)
        cout << "The string is in language.n";
    else 
        cout << "The string is not in language.n";
    return 0;

}

即使在弹出字符串中的最后一个字符后,您也要检查if(aStack.IsEmpty()),它将返回true,从而将inLanguage设置为false。因此,即使字符串是回文,在弹出最后一个字符后,您仍然将inLanguage设置为false

在pop操作的while循环之前,您没有重新初始化变量i=0。

....
 ++i; 
  //match the reverse of w 
  bool inLanguage = true; // assume string is in language 
  while(inLanguage && i < aString.length()) 
  { 
 .....

根据您的代码,while循环中的条件i < aString.length将始终为false。

在while循环之前试试这个。。

i = 0;

正如Naveen所说,while循环中的逻辑是错误的。考虑一下$a:的简单情况会发生什么

push 'a' in the stack
skip $
pop 'a' and compare with 'a' -> inLanguage == true
stack is empty -> inLanguage == false

这显然不是你想要的。您需要在循环的条件下测试堆栈大小。我会把循环简化成这样:

while (i < aString.size() && !aStack.isEmpty()) {
    char stackTop;
    aStack.pop(stackTop);
    if(stackTop != aString[i]) break;
    ++i;  
}
if (i == aString.size() && aStack.isEmpty())
    return true;
else
    return false;