题目一:

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

    博弈论——sg,mex sg性质:1.在末态的状态点为N态. 2.P态的下一步有一个是N态 3.N态的下一步全部是P态. 当然这是对于单点一个游戏的情形,也相当于NIM只有一堆石子. mex(mini ...

  2. 怎样使用Markdown

    转自:http://wowubuntu.com/markdown/basic.html 段落.标题.区块代码 一个段落是由一个以上的连接的行句组成,而一个以上的空行则会划分出不同的段落(空行的定义是显 ...

  3. java实现cmd的copy功能

    import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import ja ...

  4. 高级PHP工程师所应该具备一些技能

          很多面试,很多人员能力要求都有"PHP高级工程师的字眼",如果您真心喜欢PHP,并且您刚起步,那么我简单说说一个PHP高级工程师所应该具备的,希望给初级或已经达到中级的 ...

  5. 项目需要简单些了个WEB APP 的弹出窗

    var diag = { showDlg:'',//需要显示的DIV rushdiv:"<div id=v style='top:0;position: absolute;z-inde ...

  6. vc6.0批量编译

    一直想研究一下怎么让电脑批处理编译程序,今天就从vc6开始,做个记录,学习一下. VC可以生成make文件(Project->Export Makefile),在设置好环境变量下,执行NMAKE ...

  7. hdu 2471 简单DP

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2571 简单dp, dp[n][m] +=(  dp[n-1][m],dp[n][m-1],d[i][k ...

  8. NAND FLASH特性说明

    1.NAND FLASH 的特殊性. 1)存在坏块.由于NAND生产工艺的原因,出厂芯片中会随机出现坏块.坏块在出厂时已经被初始化,并在特殊区域中标记为不可用,在使用过程中如果出现坏块,也需要进行标记 ...

  9. QR Code簡介、介紹

    QR Code為目前最常被使用的一種二維條碼,1994年由日本Denso-Wav e公司發明,QR是英文Qu ickResponse的縮寫,即快速反應的意思,1999年時,公布了符合日本當地的標準-「 ...

  10. java selenium webdriver实战 页面元素定位

    自动化测试实施过程中,测试程序中常用的页面操作有三个步骤 1.定位网页上的页面元素,并存储到一个变量中 2.对变量中存储的页面元素进行操作,单击,下拉或者输入文字等 3.设定页面元素的操作值,比如,选 ...