您的位置:首页 > 编程语言

LeetCode(2)

2015-06-25 22:36 183 查看
Title:the length of the Last World

解题思路如下:首先要判断字符串是否为空,防止在运行程序的过程中数组下标越界

使用Java中的方法split()方法用空格符把字符串中的字母分开,分开后返回的形式是String[]数组的形式。然后使用数组的方法返回最后一个单词的长度。

java代码如下:

public class Solution {
public int lengthOfLastWord(String s) {
if (s == " ") {
return 0;
} else {
String[] string = s.split(" ");
int length = string.length;
if(length==0) {
return 0;
} else {
return string[length-1].length();
}
}
}
}


Title:计算数组中所包含的所有字符串的共同的最长前缀

解题思路如下:

首先判断数组中所包含的字符串的个数,如果个数少于两个就进行if判断一下。

遍历数组求出其中的最短字符串的长度size。

以这个最短字符串的长度进行循环遍历,分别比较数组中所有的字符串中的字母前size个是否相同,如果相同就使用StringBuilder进行保存下来,否则就停止遍历,并输出共同的最长前缀。

Java代码如下:

public class Solution {
public String longestCommonPrefix(String[] strs) {

if (strs.length==0 || strs==null) {
return "";
}
if (strs.length == 1) {
return strs[0];
}
int size = strs[0].length();
for (int i = 0; i < strs.length; i++) {
if (strs[i].length()<size) {
size = strs[i].length();
}
}
StringBuilder sb = new StringBuilder();
for (int j = 0; j < size; j++) {
char c = strs[0].charAt(j);
for (String s : strs) {
if (s.charAt(j)==c) {
c = s.charAt(j);
} else {
return sb.toString();
}
}
sb.append(c);
}
return sb.toString();
}
}


Title :Contain Duplicate

题目是用来判断所给的整形数组中是否含有相同的元素,如果有的话就返回true,否则就返回false

思路:去掉数组中重复的元素,比较去掉相同元素前后的数组的长度是否相等进行输出结果。

Python代码如下:`

class Solution:
# @param {integer[]} nums
# @return {boolean}
def containsDuplicate(self, nums):
return len(set(nums))<len(nums)


Title:calaulator the two rectangle area

思路:分别计算出两个矩形的面积减去重叠的面积,在计算重叠的面积的时候要判断两个矩形是否有重叠的部分,然后再进行计算。

public class solution {
public int computerArea(int A, int B, int C, int D, int E, int F, int G, int H) {
return computer_area(A, B, C, D)+computer_area(E, F, G, H)-OverlappingArea( A, B, C, D, E, F, G, H);
}
private int computer_Area(int i, int j, int k, int l) {
// TODO Auto-generated method stub
return (k-i)*(l-j);
}
private int OverlappingArea(int a, int b, int c, int d, int e,
int f, int g, int h) {
// TODO Auto-generated method stub
if (e>=c||f>=d||a>=g||b>=h) {
return 0;
} else {
int bl_x = Math.max(a, e);
int bl_y = Math.max(b, f);

int tr_x = Math.min(c, g);
int tr_y = Math.min(d, h);
return (tr_x-bl_x)*(tr_y-bl_y);
}
}
}


Invert Binary Tree

思路:判断根结点是否为空,不为空的话,就分别遍历左子树和右子树,最终返回整个树。

public class Solution {
public TreeNode invertTree(TreeNode root) {
if(root == null) {
return root;
}
TreeNode temp = root.left;
root.left = invertTree(root.right);
root.right = invertTree(temp);
return root;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  代码