Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

第 61 期(数据结构-栈):栈的应用 #64

Open
wingmeng opened this issue Jul 16, 2019 · 0 comments
Open

第 61 期(数据结构-栈):栈的应用 #64

wingmeng opened this issue Jul 16, 2019 · 0 comments

Comments

@wingmeng
Copy link
Collaborator

上一期介绍了 栈和栈的模拟,这一期来看看栈的应用。

依稀记得 LeetCode 看过一道判断字符串是否为回文的题,除了用反转字符串数组比较的方法外,还可以利用栈的特性来解决。

回文:如果一个字符串从前往后写和从后往前写都是一样的,则称之为回文。例如:"dad", "racecar" 就是回文。

思路:
将字符串每个字符按从左到右的顺序压入栈,当所有字符都入栈后,栈内就保存了一个天然的反转字符串,最后的字符在栈顶,第一个字符在栈底。

接下来依次弹出栈中的每个字符就可以得到一个新字符串,再和原来的字符串进行对比,如果相等,就可以判断是一个回文了。

上码:

代码中用到了上一期中的 Stack

function isPalindrome(str) {
  let stack = new Stack();

  str.split('').map(s => stack.push(s));

  let rStr = '';

  while(stack.size() > 0) {
    rStr += stack.pop();
  }

  return str === rStr;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant