leetCode解题报告5道题(十)
题目一:Valid Number
Validate if a given string is numeric.
Some examples:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true
Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.
分析:
这道题目非常easy理解,可是主要要考虑到多种情况哈.
以下我们来分析下有哪些情况须要考虑到
1、空格不能出如今数字之间(即一開始我们要消除掉字符串前后的"空格",那么之后假设再出现空格那就不满足题意了)
2、小数点和e最多仅仅能出现一次("." 和"e" (或者"E")), 如:"..2"和"0e1e1"这种字符串都是不合法的.
3、字符e之前必须有数字。e之后也要有数字, 如: "e1"或者"0e"这种字符串也不合法
4、正负号要么出如今数字的最前面,要么出如今紧接着e后面("+"或者"-" 仅仅能在“去除空格之后的字符串”的首字母出现 或者 紧跟在"e"的后面出现) 如: " +123.1 " 或者 " -12 " 或者 " 0e+6 "或者" 10e-2 "这些都是合法的
5、"e"后面的数字不能是小数(即e之后不能出现小数点)
分析完这些全部的情况。那么我们就能够開始写代码了。看代码理解吧~~~~
AC代码:
public class Solution {
public boolean isNumber(String s) {
int start = 0;
int len = s.length();
int end = len-1;
boolean flags = false;//直到处理到当前字符的时候是合法(true)还是非法(false)
boolean exitsE = false;//是否已经存在“e”
int doin = 0; //小数点的个数
//去除前面的空格 ' '
while (start < len){
if (s.charAt(start) == ' '){
start++;
}else{
break;
}
}
//去除后面的空格 ' '
while (end >= 0){
if (s.charAt(end) == ' '){
end--;
}else{
break;
}
}
//从第一个不是空格的位置開始。到最后一个不是空格的位置
for (int index=start; index<=end; ++index){
char c = s.charAt(index);
//假设开头是"+"或者"-", 那么是能够的。~~~ O(∩_∩)O
if (index == start && (s.charAt(index) == '-' || s.charAt(index) == '+')){
continue;
}
//假设"+"或者"-"紧跟在"e"或者“E”之后也是能够的!
if ((s.charAt(index) == '-' || s.charAt(index) == '+') && (s.charAt(index-1) == 'e' || s.charAt(index-1) == 'E')){
flags = false;
}else if(!((c >= '0' && c <= '9') || c == '.' || c == 'e' || c == 'E')){
//除了上面的"+"和"-"之外,假设字符不满足在 0~9 或者 . 或者 e 或者 E中的一个的话,则不合法
return false;
}else{
//假设遇到数字flags则设为合法
if ((c >= '0' && c <= '9')){
flags = true;
}else if (c == 'e' || c == 'E'){
//假设exitsE==true 表示之前的字符串已经出现过 e 或者 "E" 了,这样就有两个e了,不合法
if (exitsE){
return false;
}
exitsE = true;
//假设flags == true,表示前面有出现过数字
if (flags){
flags = false;//在把flags设置为false, 用来推断e之后是否还有出现数字
}else{
return false;
}
}else if (c == '.'){
//e后面的数字必须是整数,则假设小数点在e之后的话,直接不合法
if (exitsE){
return false;
}
//假设小数点的个数大于1则不合法
doin++;
if (doin > 1)
return false;
}else{
}
}
}
return flags;
}
}
题目二:Jump Game
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.
For example:
A = [2,3,1,1,4], return true.
A = [3,2,1,0,4], return false.
分析:
这道题目的意思挺easy理解的,我们主要讲下解法:
老规矩,我喜欢通过样例来说明解法哈,假设 A=[2, 0, 2, 0, 1] len = A.length;
我们先从第一个位置A[0]開始,然后我们用一个pos来记录如今第一个位置所能到达的最远距离。
pos = A[0] = 2;
然后我们用一个index (index < len)来记录当前的下标位置,第一个A[0]处理了之后 index++,
假设index > pos 则表示如今这个index的位置已经是 第一个元素所不能到达的地方了,这样子的话就不可能走到最后一个元素,则返回false
假设index <= pos 则 假设 A[index] + i > pos (第一个元素能走到更远的位置了),更新一下pos的值。
AC代码:
public class Solution {
public boolean canJump(int[] A) {
int len = A.length;
int index = 0;
int pos = 0;//第一个元素能到的位置
while (index < len){
if (pos < index){
//beyond
return false;
}else{
//before or equals pos
if (A[index] + index > pos){
pos = A[index] + index;
}
}
index++;
}
return true;
}
}
题目三:Jump Game II
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
For example:
Given array A = [2,3,1,1,4]
The minimum number of jumps to reach the last index is 2. (Jump 1 step
from index 0 to 1, then 3 steps to the last index.)
分析:
这题跟上面的那道题比較像。仅仅只是有点像贪心法,每一步都要走最远的那种情况,所以每一次我们都须要把全部能走到的全部位置先走一遍,看哪个最远。
AC代码:
public class Solution {
public int jump(int[] A) {
int len = A.length;
if (len == 1)
return 0;
int max = A[0];
int index = 1;
int pos = A[0];
int n = 1;
while (index < len){
if (pos >= len-1){
break;//假设pos已经能够到最后一个位置的话,结束
}
//before or equals pos
if (A[index] + index > max && index <= pos){
max = A[index] + index;//记录最大值
}
if (index == pos){
if (max > pos){
pos = max;
n++;
}
}
index++;
}
return n;
}
}
题目四:Minimum Path Sum
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
分析:
这道题目能够看做是一个动态规划的题目吧,我们举个样例
假设grid[][]=
1 2 3 4
7 8 1 3
2 5 6 10
我们从右下方的元素開始,往前推
当我们推断到 grid[2][2] == 6 时。它到右下方结点的距离为 6 + 10 = 16。 存入grid[2][2]=16;
当我们推断到 10 上方的那个元素 grid[1][3] == 3时,它到右下方结点的距离为 3 + 10 = 13, 存入grid[1][3]=13;
当推断到 grid[1][2] == 1时。 它到右下方的距离,就是 grid[1][3] 和 grid[2][2]中比較小的那个值 再加上自身的值。即grid[1][2] += min{grid[1][3] (当前元素右边的元素) , grid[2][2] (当前元素下边的元素)};
AC代码:
public class Solution {
public int minPathSum(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
for (int row=m-1; row>=0; row--){
for (int col=n-1; col>=0; col--){
//右边的列的下标
int colRight = col + 1;
//下边的行的行标
int rowDown = row + 1;
//初始值
int rowDownValue = Integer.MAX_VALUE;
int colRightValue = Integer.MAX_VALUE;
//存在行
if (rowDown < m){
rowDownValue = grid[rowDown][col];
}
//存在列
if (colRight < n){
colRightValue = grid[row][colRight];
}
//取最小
int min = rowDownValue > colRightValue ? colRightValue : rowDownValue;
//最小等于Integer.MAX_VALUE则表示没有右边也没有下边元素,即为右下方的那个目标元素
if (min != Integer.MAX_VALUE){
grid[row][col] += min;
}
}
}
return grid[0][0];
}
}
题目五:Largest Rectangle in Histogram
Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.

Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].

The largest rectangle is shown in the shaded area, which has area = 10 unit.
For example,
Given height = [2,1,5,6,2,3],
return 10.
分析:
1、暴力法:
初看题目。非常easy给人想到的方法就是暴力法,也就是说对每一个 index < len 都找到从index 往左 和 往右,直到height[index] > height[left] 和 height[index] > height[right], 然后 把int temp = height[index] * (right - left + 1) 。 假设temp > max, 则更新max的值,可是这种话一下子就TLE超时了。
TLE代码:
public class Solution {
public int largestRectangleArea(int[] height) {
int len = height.length;
int max = Integer.MIN_VALUE;
for (int i=0; i<len; ++i){
int nowHeight = height[i];
int left=i-1;
while (left>=0){
if (height[left] < nowHeight){
break;
}
--left;
}
int right=i+1;
while (right<len){
if (height[right] < nowHeight){
break;
}
++right;
}
int allSize = (right-left+1) * nowHeight;
if (allSize > max){
max = allSize;
}
}
return max;
}
}
2、借助辅助栈:
竟然暴力法不行。那我们能够知道它基本的时间消耗事实上是在寻找左边的left, 和右边的right上面,这种话有没有什么办法把这块时间节省下来,在我们遍历的过程中确定好left, right的值呢?
我们採用辅助栈( 栈中存放矩形的下标 )来做这道题目能够解决它哈。
算法描写叙述:
1、定义一个空栈
2、遍历数组 index < n
2.1、遍历到index的时候,假设“栈为空”或者height[stack.peek()] <= height[index], 这时候把 index 压入到stack中,并index++
2.2、假设不满足2.1的情况,那么证明栈顶元素p相应的height值比当前index相应的height值来得小。这种话弹出栈顶元素,并算出以栈顶元素为height所能得到的最大的矩形面积。这时候就是用辅助栈的关键地方了,针对这个情况,它的left位置就是它在栈中的下一个位置(假设没有,则表示left是0,即左边界从0開始),而它的右边界right位置就是当前index的值。
看到这里,肯定迷糊了吧,想想仅仅有当 “栈为空”或者height[stack.peek()] <= height[index] 的时候我们才会把index值压入栈中。也就是说假设把栈从上往下看,必然上面的值相应的height会比以下的大或者相等,这样以下的那个元素相应的值就必然是left的值,同理由于当 当前height[stack.peek()] >
height[index] , 我们才进行计算面积的工作,这样子的话这个index就是stack.peek()取到的这个位置相应height 的right右边界咯.
AC代码:
public class Solution {
public int largestRectangleArea(int[] height) {
int len = height.length;
if (len == 0)
return 0;
int max = Integer.MIN_VALUE;
Stack<Integer> stack = new Stack<Integer>();
int index = 0;
while (index < len){
if (stack.empty() || height[(int)stack.peek()] <= height[index]){
stack.push(index);
index++;//这里才有++哦!
}else{
//计算面积
int popIndex = (int)stack.pop();
int allWidth = stack.empty() ? index : index-((int)stack.peek())-1;
int tempValue = height[popIndex] * allWidth;
if (tempValue > max){
max = tempValue;
}
}
}
//right边界都为len
while (!stack.empty()){
int popIndex = (int)stack.pop();
int allWidth = stack.empty() ? len : len-((int)stack.peek())-1;
int tempValue = height[popIndex] * allWidth;
if (tempValue > max){
max = tempValue;
}
}
return max;
}
}
leetCode解题报告5道题(十)的更多相关文章
- leetCode解题报告5道题(六)
题目一: Longest Substring Without Repeating Characters Given a string, find the length of the longest s ...
- leetCode解题报告5道题(九)
题目一:Combinations Given two integers n and k, return all possible combinations of k numbers out of 1 ...
- leetCode解题报告5道题(七)
题目一:Interleaving String Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2 ...
- LeetCode解题报告:Linked List Cycle && Linked List Cycle II
LeetCode解题报告:Linked List Cycle && Linked List Cycle II 1题目 Linked List Cycle Given a linked ...
- leetcode解题报告(2):Remove Duplicates from Sorted ArrayII
描述 Follow up for "Remove Duplicates": What if duplicates are allowed at most twice? For ex ...
- LeetCode 解题报告索引
最近在准备找工作的算法题,刷刷LeetCode,以下是我的解题报告索引,每一题几乎都有详细的说明,供各位码农参考.根据我自己做的进度持续更新中...... ...
- leetcode 解题报告 Word Break
Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separa ...
- LeetCode解题报告—— N-Queens && Edit Distance
1. N-Queens The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no ...
- LeetCode解题报告—— Longest Valid Parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...
随机推荐
- 创建一个基于ViSP的图片显示程序
创建一个图片读取,并在windows下窗口显示的程序. #include <visp/vpDisplayD3D.h> #include <visp/vpDisplayGDI.h> ...
- python 多线程探索
前面已经了解过了,python多线程效率较低的主要原因是存在GIL,即Global Interpreter Lock(全局解释器锁).这里继续详细的看下GIL的说明与如何避免GIL的影响,从而提高py ...
- box-shadow制作各种单边,多边阴影
一.box-shadow问题探究 box-shadow 在MDN定义以及详解: box-shadow 以由逗号分隔的列表来描述一个或多个阴影效果.该属性让你可以对几乎所有元素的边框产生阴影.如果元素同 ...
- 安装成功的nginx,如何添加未编译安装模块(非覆盖安装http_image_filter_module)
背景:1.做了图片上传小项目.2.图片上传,需要多图管理.3.图片上传,需要存储到Fastdfs.4.Fastdfs上的图片,和Nginx结合.5.Nginx从Fastdfs获得的图片,需要使用缩略图 ...
- Introducing ASLR for FreeBSD
Shawn WebbOliver Pinter10 July 2014http://www.hardenedbsd.org/ [ 1. Introduction ]Security in FreeBS ...
- HDU 2846 Repository (字典树 后缀建树)
Repository Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others) Total ...
- Redisclient连接方式Hiredis简单封装使用,连接池、屏蔽连接细节
工作须要对Hiredis进行了简单封装,实现功能: 1.API进行统一,对外仅仅提供一个接口. 2.屏蔽上层应用对连接的细节处理: 3.底层採用队列的方式保持连接池,保存连接会话. 4.重连时採用时间 ...
- gvim window7 下提示乱码
今天在win7下安装gvim的时候,发现所有的提示信息都是乱码的,在网上找到了如下的解决方案.在此记录下,方便以后查阅. 以下内容转载自http://blog.csdn.net/rehung/arch ...
- 圆形头像CircleImageView和Cardview使用
效果: 圆形头像在我们的日常使用的app中很常见,因为圆形的头像比较美观. 使用圆形图片的方法可能有我们直接将图片裁剪成圆形再在app中使用, 还有就是使用自定义View对我们设置的任何图片自动裁剪成 ...
- Android 实现QQ、微信、新浪微博和百度第三方登录
前言: 对于大多数的APP都有第三方登录这个功能,自己也做过几次,最近又有一个新项目用到了第三方登录,所以特意总结了一下关于第三方登录的实现,并拿出来与大家一同分享: 各大开放平台注册账户获取AppK ...