算法打卡第四天,今天你刷题了吗
😙😙😙大家一起来刷题啊!
💓💓💓💓💓
💕💕💕💕💕
💞💞💞💞💞
💘💘💘💘💘
💖💖💖💖💖
9. 回文数
给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false 。
回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。例如,121 是回文,而 123 不是。
示例 1:
输入:x = 121
输出:true
示例 2:
输入:x = -121
输出:false
解释:从左向右读, 为 -121 。 从右向左读, 为 121-
示例 3:
输入:x = 10
输出:false
解释:从右向左读, 为 01
示例 4:
输入:x = -101
输出:false
题目分析:
水题,直接暴力判断即可.
AC代码
#include<bits/stdc++.h>
using namespace std;
//https://leetcode-cn.com/problems/palindrome-number/submissions/
bool isPalindrome(int x) {
string s = to_string(x);//abcd 2 0 1 2 3 0 1 2 1
int len = s.size();
for(int i = 0;i < len/2;i++){
if(s[i]!=s[len-1-i]){
return false;
}
}
return true;
}
int main()
{
int x = 0;
cout<<isPalindrome(x)<<endl;
return 0;
}
14. 最长公共前缀
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 “”。
示例 1:
输入:strs = ["flower","flow","flight"]
输出:"fl"
示例 2:
输入:strs = ["dog","racecar","car"]
输出:""
题目分析
水题
AC代码
#include<bits/stdc++.h>
using namespace std;
//https://leetcode-cn.com/problems/longest-common-prefix/submissions/
string longestCommonPrefix(vector<string>& strs) {
int ans = strs[0].size();
string temp = "",s =strs[0],w;
int i,j;
for(i = 1; i < strs.size(); i++) {
temp = strs[i];
w = "";
for(j = 0; j < temp.size()&&j<s.size(); j++) {//遍历字符串,同时注意下标不要越界.
if(temp[j]!=s[j]) {
if(ans > j) {
ans = j;
s = w;
}
break;
}
w += temp[j];
}
if(ans > j) {//判断是否有一方比较短,提前结束了.
ans = j;
s = w;
}
}
return s;
}
int main() {
vector<string> strs = {"dog","racecar","car"};
string ans =longestCommonPrefix(strs);
cout<<"213"<<ans<<"123"<<endl;
return 0;
}
😜😜😜😜😜今天的刷题就结束了,今天补充对前几天的算法题补充了很多(由于今天课程比较多,就刷了两道简单题,明天难度恢复.),好了,大家卷起来!😝😝😝😝😝