zoukankan      html  css  js  c++  java
  • leetCode解题报告5道题(六)

    题目一:

    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_easy_array】1010. Pairs of Songs With Total Durations Divisible by 60
    【leetcode_easy_array】1013. Partition Array Into Three Parts With Equal Sum
    【leetcode_easy_array】1122. Relative Sort Array
    【opencv基础】opencv中cv::Mat和eigen数据之间的转换
    【c++基础】测试SocketCAN的收发功能
    SRM系统与ERP系统之间存在什么联系(转)
    使用IDEA搭建一个简单的SpringBoot项目——详细过程(转)
    SpringBoot(一):使用IDEA快速搭建一个SpringBoot项目(详细)
    IntelliJ IDEA创建maven web项目(IDEA新手适用)(转)
    Maven的安装与配置(转)
  • 原文地址:https://www.cnblogs.com/mfrbuaa/p/3861255.html
Copyright © 2011-2022 走看看