1、解题思路
- 双指针法:
使用两个指针,一个从字符串的头部开始(左指针),一个从字符串的尾部开始(右指针)。比较两个指针所指的字符是否相同。如果相同,则移动两个指针向中间靠拢;如果不同,则直接返回false。当左指针超过或等于右指针时,说明所有对应的字符都相同,返回true。
- 优化:
由于字符串仅由小写字母组成,可以直接比较字符,无需额外处理。
2、代码实现
C++
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param str string字符串 待判断的字符串
* @return bool布尔型
*/
bool judge(string str) {
// write code here
int left = 0;
int right = str.size() - 1;
while (left < right) {
if (str[left] != str[right]) {
return false;
}
left++;
right--;
}
return true;
}
};
Java
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param str string字符串 待判断的字符串
* @return bool布尔型
*/
public boolean judge (String str) {
// write code here
int left = 0;
int right = str.length() - 1;
while (left < right) {
if (str.charAt(left) != str.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
}
Python
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param str string字符串 待判断的字符串
# @return bool布尔型
#
class Solution:
def judge(self , str: str) -> bool:
# write code here
left = 0
right = len(str) - 1
while left < right:
if str[left] != str[right]:
return False
left += 1
right -= 1
return True
3、复杂度分析
- 时间复杂度:O(n),其中n是字符串的长度。每个字符最多被比较一次。
- 空间复杂度:O(1),只使用了常数级别的额外空间。