leetcode 9
非常简单~坑点就是正负数情况需要分别考虑。
会了思路不是根本目的,严谨啊同学!!
class Solution {
public:
bool isPalindrome(int x) {
int ans=0;
int temp=0;
int primary=abs(x);
int fir=x;
while(x!=0)
{
temp=x%10;
x=x/10;
ans=ans*10+temp;
}
if(primary==ans&&fir==primary)
{
return true;
}
else
{
return false;
}
}
};
leetcode 10 动态规划
常规动态规划,但是我还是太菜了……今天刷完接下来一道medium两道easy要去POJ上刷刷动态规划了
题解并没有完全理解,先刷刷题找到感觉再回来看
新收获:动态规划一定要注意边界判断!!!
class Solution {
public:
bool isMatch(string s, string p) {
int lengths=s.size();
int lengthp=p.size();
bool f[lengths+1][lengthp+1];
memset(f,false,sizeof(f));
f[0][0]=true;
for(int i=0;i<=lengths;i++)
{
for(int j=1;j<=lengthp;j++)
{
if(i>0&&(s[i-1]==p[j-1]||p[j-1]=='.'))
{
f[i][j]=f[i-1][j-1];
}
if(p[j-1]=='*')
{
if(i==0||(s[i-1]!=p[j-2]&&p[j-2]!='.'))
{
f[i][j]=f[i][j-2];
}
else
{
f[i][j]=f[i-1][j]||f[i][j-1]||f[i][j-2];
}
}
}
}
return f[lengths][lengthp];
}
};
leetcode 11 某次上机的G题,题意完全一样
直觉是O(n2)的遍历,理所当然地被卡了TLE
简化方法:从两边开始向中间遍历
/*class Solution {
public:
int maxArea(vector<int>& height) {
int diameter=0;
int h=0;
int max=0;
int area=0;
int length=height.size();
for(int i=0;i<length;i++)
{
for(int j=0;j<i;j++)
{
diameter=i-j;
h=min(height[i],height[j]);
area=diameter*h;
if(max<area) max=area;
}
}
return max;
}
};*/
class Solution {
public:
int maxArea(vector<int>& height) {
int left=0;
int right=height.size()-1;
int ans;
while(left<right)
{
ans=max(ans,(right-left)*max(height[left],height[right]));
if(height[l]<height[r])
{
left++;
}
else
{
right--;
}
}
return ans;
}
};
leetcode 12 13 考啥……罗马数字表示方法?? 暂时不想写……
leetcode 14 不难,但给我的警醒是:一定要注意程序逻辑
break完了之后到底有没有跳出全部循环之类的细小问题
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
string ans="";
if(strs.empty())
{
return "";
}
if(strs.size()==1)
{
return strs[0];
}
int length=strs[0].size();
int whole=strs.size();
int number=0;
for(int i=0;i<length;i++)
{
number=0;
for(int j=1;j<whole;j++)
{
if(i<=strs[j].size()&&strs[0][i]==strs[j][i])
{
number++;
}
else if(i>strs[j].size()||strs[0][i]!=strs[j][i])
{
return ans;
}
if(number==whole-1)
{
ans+=strs[0][i];
}
}
}
return ans;
}
};