当前位置:网站首页>"125 Palindrome Verification" of the 10th day string series of LeetCode brushing questions
"125 Palindrome Verification" of the 10th day string series of LeetCode brushing questions
2022-08-11 03:59:00 【Small machine double】
LeetCode 125Palindrome verification
About palindrome,At first it seemed to be taught at schoolCWhen we were talking about language, let us write a similar topic,However, efficiency was not considered at the time,The given string is also just all letters.
回文串:Left-to-right and right-to-left look the same,例如:abba.
题目描述
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写.
说明:本题中,我们将空字符串定义为有效的回文串
Note that only letters and numbers are considered in this question,So there may be other characters that need to be excluded first.
示例
输入: “A man, a plan, a canal: Panama”
输出:true
输入: “race a car”
输出: false
The above example is because of other characters and spaces,Might not be easy to see,And the title also requires that only alphanumeric characters be considered,So remove special characters first and ignore case,如下:
amanaplanacanalpanama
It can be found that left-to-right and right-to-left are the same.
And the second example,is obviously different
raceacar
题目解析
按照题目的描述,We can remove other special characters first,The easy way is to use regular expressions:
String newString = s.toLowerCase().replaceAll("[^0-9a-z]", "");
其中:
[^0-9a-z]
表示删除所有0-9,a-z之间的字符,即Save numbers and lowercase letters.
After processing, they can be compared directly 第一个字符和最后一个字符,The second character and the penultimate character…是否相等,If they are not equal then it is not a palindrome,返回false.
The processing method can be as follows:
- 创建一个队列和栈,All elements are first enqueued and pushed onto the stack.Afterwards according to the queue(先进先出)和栈(先进后出)的性质,Compare the head element of the queue with the top element of the stack to determine whether it is a palindrome,代码如下:
public boolean isPalindrome(String s) {
if (s == "") {
return true;
}
String newString = s.toLowerCase().replaceAll("[^0-9a-z]", ""); //提前处理字符串
Queue<Character> queue = new ArrayDeque<>(); //创建队列
Stack<Character> stack = new Stack<>(); //创建栈
for (int i = 0; i < newString.length(); i++) {
queue.add(newString.charAt(i));
stack.add(newString.charAt(i));
}
for (int i = 0; i < newString.length(); i++) {
if (!queue.poll().equals(stack.pop())) {
//The head element is compared to the top element of the stack
return false;
}
}
return true;
}
程序执行结果:
The above method was given in the textbook when I learned data structure before,In fact, there is absolutely no need to use stacks and queues,A direct comparison can be done using two pointers,代码如下:
public boolean isPalindrome(String s) { if (s == "") { return true; } String newString = s.toLowerCase().replaceAll("[^0-9a-z]", ""); //提前处理字符串 for (int i = 0; i < newString.length() / 2; i++) { //It can be traversed halfway if (newString.charAt(i) != newString.charAt(newString.length() - i - 1)) { return false; } } return true; }
程序执行结果:
It can be seen that these two methods can solve the problem,But it doesn't run very fast,The reason is because regular expressions are used in advance of the string processing,比较耗费时间(串的模式匹配).
Of course it is possible to not use regular expressions,That is, without preprocessing the string,Just skip the special characters directly during each comparison.This way you can preprocess strings without invoking regular expressions.代码如下:
public boolean isPalindrome(String s) {
if (s == "") {
return true;
}
s = s.toLowerCase();
int i = 0, j = s.length() - 1; //双指针
while (i < j) {
while (!isalnum(s.charAt(i)) && i < j) i++; //Skip if it is not a character
while (!isalnum(s.charAt(j)) && i < j) j--;
if (s.charAt(i) != s.charAt(j)) {
return false;
}
//比较下一个
i++;
j--;
}
return true;
}
/** * Determines whether a character is a number or a lowercase letter * 模拟C++中的isalnum * 没有使用java中CharacterThe relevant method in the wrapper class,Speed up a bit */
public boolean isalnum(char ch) {
if (ch >= '0' && ch <= '9' || ch >= 'a' && ch <= 'z') {
return true;
}
return false;
}
边栏推荐
- AVH 动手实践 (二) | 在 Arm 虚拟硬件上部署 PP-OCR 模型
- 常见布局效果实现方案
- Getting Started with Raspberry Pi (5) System Backup
- LeetCode Brush Questions Day 11 String Series "58 Last Word Length"
- C# 一周入门高级编程之《C#-LINQ》Day Four
- 你不知道的 console.log 替代品
- The last update time of the tables queried by the two nodes of the rac standby database is inconsistent
- Leetcode 669. 修剪二叉搜索树
- Qnet弱网测试工具操作指南
- The solution to the height collapse problem
猜你喜欢
Kubernetes集群搭建Zabbix监控平台
UNI-APP_iphone bottom safe area
【Yugong Series】August 2022 Go Teaching Course 036-Type Assertion
Power Cabinet Data Monitoring RTU
Redis老了吗?Redis与Dragonfly性能比较
机器学习可以应用在哪些场景?机器学习有什么用?
Use jackson to parse json data in detail
你不知道的 console.log 替代品
【FPGA】day22-SPI protocol loopback
Provincial level of Echart maps, as well as all prefecture-level download and use
随机推荐
Binary tree related code questions [more complete] C language
What are port 80 and port 443?What's the difference?
Kubernetes集群搭建Zabbix监控平台
What should I do if the channel ServerID is incorrect when EasyCVR is connected to a Hikvision Dahua device and selects another cluster server?
[C Language] Getting Started
How to rebuild after pathman_config and pathman_config_params are deleted?
机器学习怎么学?机器学习流程
荣威imax8ev魔方电池安全感,背后隐藏着哪些黑化膨胀?
我的 archinstall 使用手册
Get the length of the linked list
"98 BST and Its Verification" of the 13th day of leetcode brushing series of binary tree series
Alibaba Cloud releases 3 high-performance computing solutions
How to delete statements audit log?
AI + medical: for medical image recognition using neural network analysis
MYSQLg advanced ------ clustered and non-clustered indexes
EasyCVR接入GB28181设备时,设备接入正常但视频无法播放是什么原因?
Common layout effect realization scheme
MYSQLg高级------聚簇索引和非聚簇索引
"3 Longest Substring Without Repeating Characters" on the 17th day of LeetCode brushing
What problems should we pay attention to when building a programmatic trading system?