leetcode第三周解题总结(5,7,66)
来源:互联网 发布:淘宝网上如何退货 编辑:程序博客网 时间:2024/06/16 17:14
5. Longest Palindromic Substring
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example:
Input: “babad”
Output: “bab”
Note: “aba” is also a valid answer.
Example:
Input: “cbbd”
Output: “bb”
题意解析:
寻找字符串中的最长回文子串
解题思路:
第一周做过一个类似的判断是否为回文字串的题目(125. Valid Palindrome),但这道题似乎就没那么简单,要找到最长的回文字串。一个思路是遍历所有的中心对称点,如果有n个字符,那么就有(2n - 1)个中心对称点,在每个对称点上用两个指针的方法寻找最长的回文字串,最后输出最长的字符串。
class Solution {public: string longestPalindrome(string s) { size_t len = s.size(); if(len == 0 || len == 1) return s; int left = 0, right = 0; for (size_t point = 0; point < len; point++) { int start = point; int end = point; while(start >= 0 && end < len && s[start]==s[end]){ start --; end ++; } if(end - start > right - left) { left = start; right = end; } start = point; end = point + 1; while(start >= 0 && end < len && s[start]==s[end]){ start --; end ++; } if(end - start > right - left) { left = start; right = end; } } return s.substr(left + 1, right - 1 -left); }};
开始第二个知识点的学习 — Math
7. Reverse Integer
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
题意解析:
32位有符号整数的翻转,如果溢出则返回0
解题思路:
数学题,思路并不难,直接看代码即可。
class Solution {public: int reverse(int x) { int y = 0; while (abs(x) > 0) { if(abs(y) > INT_MAX/10 || (abs(y) == INT_MAX/10 && (x >= 7 || x <= -8))) return 0; y = y*10 + x%10; x = x/10; } return y; }};
66. Plus One
Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.
You may assume the integer do not contain any leading zero, except the number 0 itself.
The digits are stored such that the most significant digit is at the head of the list.
题意解析:
非负整数加1,进位操作
解题思路:
只有当该数字每一位上都是9才会增加一位,而其他情况则比较简单,直接进位操作
class Solution {public: vector<int> plusOne(vector<int>& digits) { size_t len = digits.size(); for (int i = len - 1; i >= 0; i--) { if (digits[i] < 9) { digits[i] += 1; return digits; } else { digits[i] = 0; } } digits[0] = 1; digits.push_back(0); return digits; }};
- leetcode第三周解题总结(5,7,66)
- leetcode第六周解题总结(98)
- leetcode第七周解题总结
- leetcode第八周解题总结
- leetcode第十周解题总结
- leetcode第十七周解题总结
- leetcode第二周解题总结(3,8,65)
- leetcode第五周解题总结(138, 23)
- leetcode第九周解题总结(Bit Manipulation位运算)
- leetcode第十三周解题总结--动态规划(二)
- leetcode第十五周解题总结--二分查找(二)
- leetcode第十二周解题总结--动态规划
- leetcode第十六周解题总结--图
- leetcode第十八周解题总结-贪心算法
- leetcode解题总结(持续更新)
- LeetCode解题的总结(不定期更新)
- LeetCode解题思路总结
- LeetCode解题记录(7)
- 二分搜索大法
- spark statistic
- eclipse插件的安装--JavaEE--续--Java与Tomcat服务器的链接
- 递归算法的java实现(取球、全排列、反转串、杨辉三角、AB组合)
- 几种常见窗函数及其MATLAB程序实现
- leetcode第三周解题总结(5,7,66)
- Problem B: 平面上的点——Point类 (IV)
- Ubuntu 14.04 caffe 学习系列一,caffe安装only CPU
- 【数据压缩】实验一 YUV转RGB
- OpenCV运行出错:Microsoft C++ 异常: cv::Exception
- Video标签学习
- linq给现有class对象赋值
- Problem C: 平面上的点——Point类 (V)
- 微信小程序调用微信支付