14. 最长公共前缀
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 “”。
示例 1:
输入:strs = ["flower","flow","flight"]
输出:"fl"
大概思路就是把整个字符串数组遍历一下,得到它的每一项,
- flower
- flow
- flight
str[0] [0] = str[1] [0] = str[2] [0]
双重循环,对比每一项对应的字符是否相等,一旦出现不相等的情况,截取出来
ans = ans.slice(0,j);
/**
-
@param {string[]} strs
-
@return {string}
*/
var longestCommonPrefix = function(strs) {
if (strs.length === 0) {
return “”;
}let ans = strs[0];
for (let i = 0;i< strs.length;i++) {let j = 0 for (;j < ans.length;j++) { if (ans[j] !== strs[i][j]) { break; } } ans = ans.slice(0,j); if (ans === "") { return ""; }}
return ans
};
125. 验证回文串
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串。
示例 1:
输入: "A man, a plan, a canal: Panama"
输出: true
解释:"amanaplanacanalpanama" 是回文串
思路:这里首先有个问题是需要将不是字符的项去除,或者是不参与比较
新增一个方法,处理不是字符串的项,
const isVild = function (c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9');
}
再使用双指针,左指针指向的是0索引,右指针指向str.length - 1;
如果左右指针指向的值不是字符串,那么向前或者向右移动一位
while (i < j) {
if (!isVild(s[i])) {
i++
continue
}
if (!isVild(s[j])) {
j--
continue
}
比较两个指针对应的项是否相等,如果不相等,返回false
否则:左指针++,右指针–
/**
* @param {string} s
* @return {boolean}
*/
var isPalindrome = function(s) {
s = s.toUpperCase();
let i = 0;
let j = s.length - 1
while (i < j) {
if (!isVild(s[i])) {
i++
continue
}
if (!isVild(s[j])) {
j--
continue
}
if (s[i] !== s[j]) {
return false;
}
i++;
j--
}
return true
};
const isVild = function (c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9');
}
本文介绍两种字符串处理技巧:一是寻找字符串数组中的最长公共前缀的方法;二是验证一个字符串是否为回文串,通过去除非字母数字字符并忽略大小写进行判断。
1158

被折叠的 条评论
为什么被折叠?



