[LeetCode] March 16 punch card -Day1

1 title string compression

description

String compression. Using the number of recurring characters, written in a way to achieve the basic string compression. For example, the string aabcccccaaa becomes a2b1c5a3. If the string "compressed" not shorter, the original string is returned. You may assume the string contains only the case letters (a to z).
Example 1:
Input: "aabcccccaaa"
Output: "a2b1c5a3"
Example 2:
Input: "abbccd"
Output: "abbccd"
Explanation: the "abbccd" compressed "a1b2c2d1", the string length is longer than the original.

achieve

class Solution {
    public String compressString(String S) {
        if(S.length() == 0){
            return "";
        }
        StringBuilder sb = new StringBuilder();
        char[] chars = S.toCharArray();
        int index = 0;
        int count = 0;
        for(int i = 0; i < S.length()-1; i++){
            count++;
            if(chars[i] != chars[i+1]){
                sb.append(chars[i]).append(count);
                index = i + 1;
                count = 0;
            }
        } 
        sb.append(chars[index]).append(chars.length - index);
        String result = sb.toString();
        return  result.length() < S.length() ? result : S;
    }
}

notes

  1. StringBuilder
    in the program development process, we often encounter situations string concatenation, convenient and direct way is to be achieved by "+" sign, but this approach to achieve the purpose of efficiency is relatively low, and each execution will create a String object, that is time consuming and a waste of space. Use StringBuilder class to avoid this problem.
1append(String str)/append(Char c):字符串连接
System.out.println("StringBuilder:"+strB.append("ch").append("111").append('c'));
//return "StringBuilder:ch111c"

2toString():返回一个与构建起或缓冲器内容相同的字符串
System.out.println("String:"+strB.toString());
//return "String:ch111c"

3appendcodePoint(int cp):追加一个代码点,并将其转换为一个或两个代码单元并返回this
System.out.println("StringBuilder.appendCodePoint:"+strB.appendCodePoint(2));
//return "StringBuilder.appendCodePoint:ch111c"

4setCharAt(int i, char c):将第 i 个代码单元设置为 c(可以理解为替换)
strB.setCharAt(2, 'd');
System.out.println("StringBuilder.setCharAt:" + strB);
//return "StringBuilder.setCharAt:chd11c"

5insert(int offset, String str)/insert(int offset, Char c):在指定位置之前插入字符()
System.out.println("StringBuilder.insertString:"+ strB.insert(2, "LS"));
//return "StringBuilder.insertString:chLSd11c"
System.out.println("StringBuilder.insertChar:"+ strB.insert(2, 'L'));
//return "StringBuilder.insertChar:chLLSd11c"

6delete(int startIndex,int endIndex):删除起始位置(含)到结尾位置(不含)之间的字符串
System.out.println("StringBuilder.delete:"+ strB.delete(2, 4));
//return "StringBuilder.delete:chSd11c"
  1. Not append the last letter in a for loop, a recording start position of the index letter, character string length by subtracting the length of the index position that is the same letter.

Question 2

description

Roman numeral characters comprising the following seven: I, V, X, L , C, D and M.
Numerical character
the I. 1
V. 5
X-10
L 50
C 100
D 500
M 1000
, for example, 2 written as Roman numerals II, namely 1.12 written as two parallel XII, namely X + II. 27 written as XXVII, namely XX + V + II.
Typically, small numbers of Roman numerals to the right in large numbers. But there are exceptions, for example, do not write 4 IIII, but IV. In the left number 5 number 1, the number of large numbers equal to the value represented by a reduced number 5 obtained 4. Likewise, the number 9 is represented as IX. This special rule applies only to the following six cases:
the I can be placed on the left side of V (5) and X (10), and to represent 4 and 9.
X L can be placed on the left (50) and C (100), and 40 and 90 are represented.
C may be placed on D (500) and M (1000) to the left, to 400 and 900 represent.
Given a Roman numeral, to convert it to an integer. To ensure that the input is in the range of 1 to 3999.
Example 1:
Input: "LVIII"
Output: 58
explains: L = 50, V = 5 , III = 3.
Example 2:
Input: "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90, IV = 4.

achieve

class Solution {
    public int romanToInt(String s) {
        Map<Character,Integer> map = new HashMap<>();
        map.put('I',1);
        map.put('V',5);
        map.put('X',10);
        map.put('L',50);
        map.put('C',100);
        map.put('D',500);
        map.put('M',1000);
        int len = s.length();
        int sum = map.get(s.charAt(len-1));
        for(int i = len - 2; i >= 0; --i){
            if(map.get(s.charAt(i)) < map.get(s.charAt(i+1))){
                sum -= map.get(s.charAt(i));
            } else{
                sum += map.get(s.charAt(i));
            }
        }
        return sum;
    }
}

notes

  1. Java dictionary definition: Map <Character, Integer> map = new HashMap <> (), insertion map.put (a, b), according to the key value to return dictionary map.get (a), return b.
  2. String type element values ​​may be obtained by the method specified position charAt (index) is.

Problem 3 longest common prefix

description

Write a function to find the longest common prefix string array.
If there is no common prefix, it returns an empty string "."
Example 1:
Input: [ "flower", "flow ", "flight"]
Output: "FL"
Example 2:
Input: [ "dog", "racecar ", "car"]
Output: ""
Explanation: there is no input common prefix.

achieve

class Solution {
    public String longestCommonPrefix(String[] strs) {
        int len = strs.length;
        if(len == 0) return "";
        int min = 0x7fffffff;
        for(int i = 0; i < len; i ++){
            if(strs[i].length() < min){
                min = strs[i].length();
            }
        }
        for(int j = 0; j < min; j++){
            for(int i = 1; i < len; i++){
                if(strs[0].charAt(j) != strs[i].charAt(j)){
                    return strs[0].substring(0,j);
                }
            }
        }
        return strs[0].substring(0,min);
    }
}

notes

  1. 0x7fffffff to int maximum
  2. Recording position of the same minimum
Published 29 original articles · won praise 65 · views 5039

Guess you like

Origin blog.csdn.net/xd963625627/article/details/104903153