3.2 Use the stack to determine the palindrome character vector

Topic: A palindrome refers to a character sequence that is the same both in front and back. For example, "abba" and "abdba" are both palindrome, but "good" is not a palindrome. Try to write an algorithm to determine whether a given character vector is a palindrome.

Algorithm idea:
According to the examples in the title, it is necessary to classify and discuss according to the number of characters in the character vector.
1. When the length of the character vector is an even number , the number of characters pushed into the stack is exactly half of the character vector; when the stack is not empty, the top elements of the stack are sequentially popped out of the stack and compared with the elements in the second half of the character vector. The top element is different from the current character vector, indicating that it is not a palindrome character vector, and FALSE is returned; otherwise, the new stack top element is compared with the next character until the stack is empty, indicating that it is a palindrome vector.
2. When the length of the character vector is odd , the characters in the middle need to be skipped; the characters before the middle character are pushed onto the stack, and the elements in the stack are compared with the characters after the middle character in turn.

Algorithm Description:

int IsHuiwen(SqStack &S,char str[]){
	int length=strlen(str); //length表示字符向量的长度
	int m=length/2;   //m表示字符向量长度的一半,用m将字符向量分成两部分
	char top;     //定义一个字符型变量top,用来表示栈顶元素的值
	for(i=0;i<m;i++){
		Push(S,str[i])  //调用Push函数将前一半字符插入栈S
		}
	if(length%2==0){    //当字符向量的长度为偶数时
		while(!IsEmpty(S)){  //若栈不为空,执行此循环
			Pop(S,top);       //调用出栈函数,栈顶元素出栈,并将栈顶元素赋值给变量top
			if(top!=str[i]){  //栈顶元素和对应的字符不同
				return 0;  //退出循环,不是回文字符向量
			}else{       //栈顶元素和对应的字符相同, 取后一个字符,继续执行此循环
				i++; 
			}
		}
	}else{         //当字符向量的长度为奇数时
		i=i+1;      //跳过中间字符
		while(!IsEmpty(S)){     //同上
			Pop(S,top);
			if(top!=str[i]){
				return 0;
			}else{
				i++;
			}
		}
	}
	return 1;      //循环执行结束,直到栈空,说明是回文字符向量
}

Guess you like

Origin blog.csdn.net/qq_39688282/article/details/108062473
Recommended