Conditional judgment string (queue implementation)

Conditional judgment string (queue implementation)


  • I wrote a stack to implement it before: the basic algorithm problem of the stack - the conditional judgment string . The title is also included in this blog, so it will not be described here.
  • This time, it is implemented using a simple queue structure, and the basic operation functions are in another blog: Basic operations of queues (simple version) .
  • The idea is as follows:
    1. First use a character array to store the string to be judged
    2. Determine whether the string is an empty string, if so, end directly; if not, go to the next step
    3. Determine whether the string ends with '@', if not, end directly; if so, go to the next step
    4. enqueue characters before '&'
    5. If all elements in the character array are enqueued, it proves that the string does not contain '&', return FALSE
    6. The characters in the queue are dequeued, and the elements before the '@' in the remaining character array are compared. If there are different characters in the middle, it will end directly and return FALSE. Returns TRUE until all characters are matched and all characters are matched.

The following are the specific functions:

Status CharMatch(char str[]){
    int len = strlen(str);          // 得到字符串长度

    if (len == 0)return ERROR;      // 若是空串,则直接结束,并返回ERROR
    if (str[len-1] != '@')return ERROR;     // 输入字符串格式不对

    //栈的初始化
    SqQueue *Q;
    Q = (SqQueue *)malloc(sizeof(SqQueue));
    InitQueue(Q);

    //将要判断的字符串入栈
    int i = 0;
    while (str[i] != '&'){
        EnQueue(Q, str[i]);
        i++;
    }

    if (i == len)return FALSE;  //若指针已经移动了字符串长度次,则证明不含‘&’,直接返回FALSE

    i = 0;
    while (str[len - 2 - i] != '&'){
        if (str[len - 2 - i] != DeQueue(Q))     // 若字符串中后面对应位置与前面的对不上,证明该字符串不符合条件,返回FALSE
            return FALSE;

        i++;                    //指针后移
    }

    return TRUE;
}

In the main function, I directly wrote the experimental data in it. If readers are interested, they can use scanf() to accept the user's data

int main()
{

    char str[] = "123&4321@";

    int n = CharMatch(str);

    printf("--------->%d\n", n);
    system("pause");
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325689801&siteId=291194637