题目一:

Longest Substring Without Repeating Characters

Given
a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

分析:

这道题目的事实上考察的就是指针问题而已,因为我是用java,就相当于两个变量相应两个下标,来移动这两个下标就能够解决问题了。

我拿一个样例来说明这道题目吧:

如:字符串:wlrbbmqbhcdarzowkkyhiddqscdxrjmowfrxsjybldbefsarcbynecdyggxxpklorellnmpapqfwkhopkmco

思想:我们能够知道,依照顺序下去,当下标pos指向 “4” (第二个字符b) 时,我们知道,这样子的话,前面的长度就被确定了,就是4了,下次,当我们要再算下一个不反复子串的长度的时候便仅仅能从这个下标为4的字符開始算了。

依据这种简要分析,我们要注意这道题目的陷阱

1、字符并不仅仅是a-z的字母,有可能是其它的特殊字符或者阿拉伯数字等等,这样子我们能够想到我们或许须要256个空间(ASCII码总数)来存储每一个字符上一次出现的位置下标信息。我们记作 position[i],  i 表示字符 c 的 ASCII编码, position[i]
表示字符 c 上一次出现的位置下标。

2、我们须要一个下标变量来指向此次子串的開始位置,记做 start 变量,当下次 pos 指向的当前字符 相应的值 position[i] 的位置在 start 变量的前面的话,那么我们就忽略不考虑(由于我们这次计算子串是从start開始的,所曾经面的出现反复的字符就无论了)

分析完了之后,我们就看下代码里面的解释吧!

AC代码:

package cn.xym.leetcode;

/**
* @Description: [计算不反复子串]
* @Author: [胖虎]
* @CreateDate: [2014-4-26 下午7:19:25]
* @CsdnUrl: [http://blog.csdn.net/ljphhj]
*/
public class Solution {
public int lengthOfLongestSubstring(String s) {
if (s == null || s.equals("")){
return 0;
}
int len = s.length();
int[] position = new int[256];//256:相应ASCII码总数
int maxLength = 0; //子串開始位置默觉得-1
int start = -1;
//初始化全部字符的位置下标都为-1
for (int i=0; i<256; ++i){
position[i] = -1;
}
//遍历字符串
for (int pos=0; pos<len; ++pos){
char c = s.charAt(pos);
//注: 当出现的反复字符串的位置在start后面的话,我们才更新下一次计算子串的起始位置下标
if (position[c] > start){
start = position[c];
}
if (pos - start> maxLength){
maxLength = pos - start;
}
position[c] = pos;
}
return maxLength;
}
public static void main(String[] args) {
int result = new Solution().lengthOfLongestSubstring("wlrbbmqbhcdarzowkkyhiddqscdxrjmowfrxsjybldbefsarcbynecdyggxxpklorellnmpapqfwkhopkmco");
System.out.println(result);
}
}

题目二:

Rotate Image

You are given an n x n 2D matrix representing an image.

Rotate the image by 90 degrees (clockwise).

Follow up:

Could you do this in-place?

分析:题目要求我们把一个二维的矩阵在原数组上做顺时针90度的旋转。这道题目事实上仅仅须要在草稿纸上把图一画,不难发现,事实上矩阵仅仅须要通过一次 对角线(“ \ ”) 的翻转,然后再经过一次 竖直线(" | ")的翻转就能够得到我们终于想要的结果!

AC代码:

public class Solution {
public void rotate(int[][] matrix) {
int n = matrix.length;
for (int i=1; i<n; ++i){
for (int j=0; j<i; ++j){
matrix[i][j] = matrix[i][j] + matrix[j][i];//a = a + b;
matrix[j][i] = matrix[i][j] - matrix[j][i];//b = a - b;
matrix[i][j] = matrix[i][j] - matrix[j][i];//a = a - b;
}
}
int middle = n / 2;
for (int i=0; i<n; ++i){
for (int j=0; j<middle; ++j){
matrix[i][j] = matrix[i][j] + matrix[i][n-j-1];
matrix[i][n-j-1] = matrix[i][j] - matrix[i][n-j-1];
matrix[i][j] = matrix[i][j] - matrix[i][n-j-1];
}
}
}
}



题目三:

Restore IP Addresses

Given a string containing only digits, restore it by returning all possible valid IP address combinations.

For example:

Given "25525511135",

return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)

分析:做这道题目之前我们首先要明确一些基本概念。首先ipV4地址一共由4位组成,4位之前用"."隔开,每一位必须满足是数字从0到255的范围内。假设字符串随意组合之后,满足了一共同拥有4位,而且每一位都合法的话,那么这个字符串便是满足题意的字符串了。我们能够将它增加结果集。

解题思路:竟然是做这样的多种情况的,非常明显我们要用递归的方法来解决,而递归有个终止状态,终止状态我们非常easy知道就是剩下要处理的字符串的长度为0了,这时候我们再推断已经得到的字符串是否是合法的Ip就可以。具体的看代码和凝视理解!

AC代码:(436ms)

package cn.xym.leetcode;

import java.util.ArrayList;
import java.util.List;
/**
*
* @Description: [求合法的IP Address]
* @Author: [胖虎]
* @CreateDate: [2014-4-28 下午1:56:22]
* @CsdnUrl: [http://blog.csdn.net/ljphhj]
*/
public class Solution {
private ArrayList<String> list = new ArrayList<String>();
public ArrayList<String> restoreIpAddresses(String s) {
/*预处理,防止一些无谓的计算*/
if (s == null)
return list;
int len = s.length();
//此条件的字符串都不可能是合法的ip地址
if (len == 0 || len < 4 || len > 12)
return list;
//递归
solveIpAddress("", s);
return list;
}
/**
* 递归求解ipAddress
* @param usedStr 当前已经生成的字符串
* @param restStr 当前还剩余的字符串
*/
public void solveIpAddress(String usedStr, String restStr){
/* 递归结束条件:当剩余的字符串restStr长度为0时,而且已经生成的字符串usedStr是合法的IP地址时,
* 增加到结果集合list中。
* */
if (restStr.length() == 0 && isVaildIp(usedStr)){
list.add(usedStr);
}else{
/* 剩余的字符串长度假设大于等于3,因为每个位的Ip地址最多是0~~255,所以我们仅仅须要循环3次
* 但假设剩余的字符串长度len不大于3,我们仅仅须要循环len次就可。
* */
int len = restStr.length() >= 3 ? 3 : restStr.length(); for (int i=1; i<=len; ++i){
//推断子串是否符合ip地址的每一位的要求
if (isVaild(restStr.substring(0,i))){
String subUsedStr = "";
if (usedStr.equals("")){
subUsedStr = restStr.substring(0,i);
}else{
subUsedStr = usedStr + "." + restStr.substring(0,i);
}
String subRestStr = restStr.substring(i); solveIpAddress(subUsedStr,subRestStr);
} }
}
}
/**
* 验证字符串ip_bit是否满足ip地址中一位的要求
* @param ip_bit
* @return
*/
public boolean isVaild(String ip_bit){
if (ip_bit.charAt(0) == '0' && ip_bit.length() > 1){
return false;
}
Integer ip_bit_number = Integer.parseInt(ip_bit);
if (ip_bit_number >= 0 && ip_bit_number <= 255){
return true;
}else{
return false;
}
}
/**
* 验证ipAddress是否满足一个合法Ip的要求
* @param ipAddress
* @return
*/
public boolean isVaildIp(String ipAddress){
int count = 0;
for (int i=0; i<ipAddress.length(); ++i){
if (ipAddress.charAt(i) == '.'){
count++;
}
}
if (count == 3){
return true;
}
return false;
}
public static void main(String[] args) {
Solution s = new Solution();
List<String> list = s.restoreIpAddresses("010010");
for (String str : list){
System.out.println(str);
}
}
}





AC代码:(网友提供,392ms)

public class Solution {
public ArrayList<String> restoreIpAddresses(String s) {
ArrayList<String> result = new ArrayList<String>();
String tempIP = null;
for (int i = 1;i<s.length();i++){
if(i<=3&&(s.length()-i)<=9&&(s.length()-i)>=3){
for (int j=i+1;j<s.length();j++){
if(j-i<=3&&(s.length()-j)<=6&&(s.length()-i)>=2){
for (int k=j+1;k<s.length();k++){
if ((k-j)<=3&&(s.length()-k)<=3){
String n1 = s.substring(0, i);
String n2 = s.substring(i, j);
String n3 = s.substring(j, k);
String n4 = s.substring(k, s.length());
if (!(n1.charAt(0) =='0'&& n1.length()>1)&&
!(n2.charAt(0) =='0'&& n2.length()>1)&&
!(n3.charAt(0) =='0'&& n3.length()>1)&&
!(n4.charAt(0) =='0'&& n4.length()>1)&&
Integer.parseInt(n1)<256&&Integer.parseInt(n2)<256&&
Integer.parseInt(n3)<256&&Integer.parseInt(n4)<256){
tempIP = n1+"."+n2+"."+n3+"."+n4;
result.add(tempIP);
}
}
}
}
}
}
}
return result;
}
}



题目四:

ZigZag Conversion(挺恶心的,题目看懂就相当于做完了)

The string "PAYPALISHIRING" is written in a zigzag pattern on a given
number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

P   A   H   N
A P L S I I G
Y I R

And then read line by line: "PAHNAPLSIIGYIR"

Write the code that will take a string and make this conversion given a number of rows:

string convert(string text, int nRows);

convert("PAYPALISHIRING",
3)
 should return "PAHNAPLSIIGYIR".

分析:仅仅是把字符串先依照" 反N " [即: | / |  ]的形状“平铺”,然后把之后得到的一行的字符串串起来就得到了最后的结果字符串。

须要注意的是,两竖之间的“过度” " / " 那一列的行数为 nRows - 2; 而其它的列为nRows行

这样讲太难理解了,看图解理解一下吧!

图解:

细致观察这个题目的规律是解决这道题目的关键,比方它有几个陷阱,一个是中间夹着的短边" / " 的长度问题,还有一个是方向问题,“ | ”的方向是从上往下,而“ / ” 的方向是从下往上的.

AC代码:

package cn.xym.leetcode;
/**
*
* @Description: [ZigZag Conversion]
* @Author: [胖虎]
* @CreateDate: [2014-4-28 下午11:52:27]
* @CsdnUrl: [http://blog.csdn.net/ljphhj]
*/
public class Solution {
public String convert(String s, int nRows) {
if (s == null || s.equals("") || nRows == 1){
return s;
}
//定义行数nRows相应的字符串数组, arrays[0] 表示第一行相应的字符串
String[] arrays = new String[nRows];
for (int i=0; i<nRows; ++i){
arrays[i] = "";
} int strLen = s.length();
int nowRindex = 1;
//推断是否是中间的过渡列 "/"
boolean isMiddle = false;
//遍历字符串
for (int i=0; i<strLen; ++i){
arrays[nowRindex-1] += s.charAt(i);
if (isMiddle == false){
//从上往下
nowRindex++;
if (nowRindex == nRows + 1) {
if (nRows == 2) {
nowRindex = 1;
} else {
isMiddle = true;
nowRindex = nRows - 1;
}
}
}else{
//从下往上
nowRindex--;
if (nowRindex == 1){
isMiddle = false;
nowRindex = 1;
}
}
}
StringBuffer buffer = new StringBuffer();
for (int i=0; i<arrays.length; ++i){
if (arrays[i] != null && !arrays[i].equals("")){
buffer.append(arrays[i]);
}
}
return buffer.toString();
}
public static void main(String[] args) {
Solution s = new Solution();
System.out.println(s.convert("PAYPALISHIRING", 4));
}
}

题目五:

Set Matrix Zeroes

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.

click to show follow up.

Follow up:

Did you use extra space?

A straight forward solution using O(mn) space is probably a bad idea.(1)

A simple improvement uses O(m + n) space, but still not the best solution.(之后补上)

Could you devise a constant space solution?(之后补上)

分析:题意比較easy理解,可是它的条件我并没全然满足,可是能够AC,明天再看看哈!

AC代码:(1)

public class Solution {
public void setZeroes(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
boolean[][] flags = new boolean[m][n]; for(int row=0; row<m; ++row){
for (int col=0; col<n; ++col){
if (matrix[row][col] == 0){
flags[row][col] = true;
}else{
flags[row][col] = false;
}
}
} for (int row=0; row<m; ++row){
for (int col=0; col<n; ++col)
if (flags[row][col] && matrix[row][col] == 0){
for (int i=0; i<n; ++i){
matrix[row][i] = 0;
}
for (int i=0; i<m; ++i){
matrix[i][col] = 0;
}
}
}
}
}



leetCode解题报告5道题(六)的更多相关文章

  1. leetCode解题报告5道题(九)

    题目一:Combinations Given two integers n and k, return all possible combinations of k numbers out of 1 ...

  2. leetCode解题报告5道题(七)

    题目一:Interleaving String Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2 ...

  3. leetCode解题报告5道题(十)

    题目一:Valid Number Validate if a given string is numeric. Some examples: "0" => true &quo ...

  4. LeetCode解题报告:Linked List Cycle && Linked List Cycle II

    LeetCode解题报告:Linked List Cycle && Linked List Cycle II 1题目 Linked List Cycle Given a linked ...

  5. leetcode解题报告(2):Remove Duplicates from Sorted ArrayII

    描述 Follow up for "Remove Duplicates": What if duplicates are allowed at most twice? For ex ...

  6. LeetCode 解题报告索引

    最近在准备找工作的算法题,刷刷LeetCode,以下是我的解题报告索引,每一题几乎都有详细的说明,供各位码农参考.根据我自己做的进度持续更新中......                        ...

  7. leetcode 解题报告 Word Break

    Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separa ...

  8. 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 ...

  9. LeetCode解题报告—— Longest Valid Parentheses

    Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...

随机推荐

  1. MarkDown使用 (三)表格

    MarkDown表格的用法 MarkDown表格的用法 例如: $$ \begin{array}{c|lcr} n & \text{Left} & \text{Center} & ...

  2. JS 操作日期

    var myDate = new Date(); myDate.getYear(); //获取当前年份(2位) myDate.getFullYear(); //获取完整的年份(4位,1970-???? ...

  3. poj 2688 Cleaning Robot bfs+dfs

    题目链接 首先bfs, 求出两两之间的距离, 然后dfs就可以. #include <iostream> #include <cstdio> #include <algo ...

  4. Android学习路径图

    一个PHPer转战Android学习过程: 直接跨过java的学习,原因有我之前看过毕向东和张孝祥的Java基础课程,虽然中间好几次看睡着,但java的环境是能跑起来的.我建议大家如果没有Java基础 ...

  5. android HTTP发送及MD5加密收集

    发送部分: public void MyFunction{ HttpClient httpclient = new DefaultHttpClient(); //你的URL HttpPost http ...

  6. C功底挑战Java菜鸟入门概念干货(一)

    一.认识Java 1.Java 程序比较特殊,它必须先经过编译,然后再利用解释的方式来运行.  2.Byte-codes 最大的好处是——可越平台运行,可让“一次编写,处处运行”成为可能.  3.使用 ...

  7. 【Perl学习笔记】2. perl中的bless理解

    bless有两个参数:对象的引用.类的名称. 类的名称是一个字符串,代表了类的类型信息,这是理解bless的关键. 所谓bless就是把 类型信息 赋予 实例变量. 程序包括5个文件:person.p ...

  8. D3.js学习记录【转】【新】

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  9. ASP.NET之电子商务系统开发-3(订单)

    一.前言 继上次的购物车,这是第三篇.记录一下订单功能.这功能做的时候,走过弯路,很是烧脑,因为思路没理顺,数据库设计的也不怎么好,做到一半才发现有问题,接着把数据库重新设计好,理清思路后,终于完成了 ...

  10. fullPage.js插件用法(转发)

    fullPage.js主要功能有: 支持鼠标滚动 支持前进后退和键盘控制 多个回调函数 支持手机.平板触摸事件 支持 CSS3 动画 支持窗口缩放 窗口缩放时自动调整 可设置滚动宽度.背景颜色.滚动速 ...