2021/11/21, Swordfinger offer--Simulation

Keywords: Java string array Simulation

JZ29 Clockwise Print Matrix

Title Address
describe
Enter a matrix to print out each number in clockwise order from outside to inside, for example, if you enter the following 4 X 4 matrix:
[[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,16]]
Print out the numbers in turn
[1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10]
Data Range:
0 <= matrix.length <= 100
0 <= matrix[i].length <= 100

Example 1

Input:
[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
Return value:
[1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10]

Example 2

Input:
[[1,2,3,1],[4,5,6,1],[4,5,6,1]]
Return value:
[1,2,3,1,1,1,6,5,4,4,5,6]

Code

import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> printMatrix(int [][] matrix) {
        ArrayList<Integer> res=new  ArrayList<Integer> ();
        for(int i=0,j=0,cols=matrix[0].length,rows=matrix.length;cols>0&&rows>0;i++,j++){
            res.addAll(printMatrix(matrix,i,j,rows,cols));
            cols-=2;
            rows-=2;
        }
        return res;
    }
    //Array from upper left corner (si,sj) to lower right corner (si+rows-1,sj+cols-1) forms an array and prints clockwise from upper left corner
    public ArrayList<Integer> printMatrix(int [][] matrix,int si,int sj,int rows,int cols) {
        ArrayList<Integer> res=new  ArrayList<Integer> ();
        if(rows==1){
            for(int j=sj;j<sj+cols;j++) res.add(matrix[si][j]);
        }else if(cols==1){
            for(int i=si;i<si+rows;i++) res.add(matrix[i][sj]);
        }else{
            for(int j=sj;j<sj+cols-1;j++) res.add(matrix[si][j]);
            for(int i=si;i<si+rows-1;i++) res.add(matrix[i][sj+cols-1]);
            for(int j=sj+cols-1;j>sj;j--) res.add(matrix[si+rows-1][j]);
            for(int i=si+rows-1;i>si;i--) res.add(matrix[i][sj]);
        }
        return res;
    }
}

JZ61 Poker Shunzi

Title Address
describe
Now there are two decks of poker cards, and five cards are randomly assigned from the decks. We need to decide if they are smooth or not.
There are the following rules:

  1. A is 1, J is 11, Q is 12, K is 13, A cannot be considered 14
  2. Da Wang and Xiao Wang are 0, 0 can be regarded as any card
  3. If the five cards given make up a sequence (that is, the five cards are continuous), output true, otherwise output false.
    4. Data guarantees 5 numbers per group, each group contains up to 4 zeros, and the values of arrays are [0, 13]

Requirements: Spatial Complexity O(1), Time Complexity O(nlogn), and there is also a solution to this topic with Time Complexity O(n)
Enter a description:
Enter the value of five playing cards
Return value description:
Can five playing cards make up a smooth son?
Example 1

Input:
[6,0,2,0,4]
Return value:
true
 Explain:
The two zeros in the middle are considered as 3 and the other as 5. That is:[6,3,2,5,4]
So these five cards are in[2,6]Interval continuous, output true 

Example 2

Input:
[0,3,2,6,4]
Return value:
true

Example 3

Input:
[1,0,0,1,0]
Return value:
false

Example 4

Input:
[13,12,11,0,1]
Return value:
false

Code

public class Solution {
    public boolean IsContinuous(int [] numbers) {
        //minVal:numbers array minimum maxVal:numbers array maximum
        int minVal=Integer.MAX_VALUE,maxVal=Integer.MIN_VALUE;
        //mark[elem]=m: Indicates that there are m elems in the numbers array
        int[] mark=new int[20];
        //zero denotes the number of zeros, 0 can denote any number, which is discussed separately
        int zero=0;
        for(int elem:numbers){
            mark[elem]++;
            minVal=elem!=0&&elem<minVal?elem:minVal;
            maxVal=elem>maxVal?elem:maxVal;
            if(elem==0) zero++;
        }
        //If Maximum-Minimum >=5, the interval is too large to fill with 0
        //For example: [1,2,0,4,6] 6-1>=5, so it cannot be filled with 0, so it cannot be cistron
        if(maxVal-minVal>=5) return false;
        //Try to fill the gap between the minimum and maximum with 0, and if 0 is not enough, it will not form a cis.
        for(int i=minVal;i<=maxVal;i++){
            if(mark[i]==0){
                if(zero>0) zero--;
                else return false;
            }else if(mark[i]>1){
                return false;
            }
        }
        return true;
    }
}

JZ67 converts strings to integers (atoi)

Title Address
describe
Write a function, StrToInt, that converts strings to integers. You cannot use atoi or other similar library functions. The incoming string may consist of the following parts:
1. Several spaces
2. (Optional) A symbol character ('+'or'-')
3. String expressions consisting of numbers, letters, symbols, and spaces
4. Several spaces

The conversion algorithm is as follows:
1. Remove useless leading spaces
2. When the first non-empty character is a + or - sign, the plus or minus sign is used as the integer. If there is no sign, the default is a positive number
3. Determine the effective part of an integer:
3.1 Once the symbol bits have been determined, they are combined with as many consecutive numbers as possible to become valid integer numbers. If there is no valid integer part, 0 is returned directly
3.2 Remove the integer part in front of the string, followed by extra characters (letters, symbols, spaces, etc.) that can be ignored and should not affect the function
3.3 Integer exceeds the range of 32-bit signed integers [2^31, 2^31_1], and needs to be truncated to keep it within this range. Specifically, integers less than 2^31 should be adjusted to 2^31, and integers greater than 2 ^31_1 should be adjusted to 2 ^31_1
4. Remove unnecessary trailing spaces

Data Range:
1.0 <=String Length <= 100
2. Strings consist of English letters (upper and lower case), numbers (0-9),'','+','-'and'.'

Example 1

Input:
"82"
Return value:
82

Example 2

Input:
"   -12  "
Return value:
-12
 Explain:
Remove the space before and after, for-12  

Example 3

Input:
"4396 clearlove"
Return value:
4396
 Explain:
6 The following characters are not part of a valid integer, removed, but returned to the valid part extracted earlier  

Example 4

Input:
"clearlove 4396"
Return value:
0

Example 5

Input:
"-987654321111"
Return value:
-2147483648

Code

import java.util.*;
public class Solution {
    /**
     * The class name, method name and parameter name in the code have been specified. Do not modify them, just return to the value specified by the method.
     *
     * 
     * @param s string Character string 
     * @return int integer
     */
    public int StrToInt (String s) {
        // write code here
        char[] strs=s.trim().toCharArray();//Remove whitespace before and after
        boolean isNum=true;//Determine whether it is a legal number
        boolean isPositive=true;//Determine if it is a positive number
        int num=0;//Record the integer part of a number
        //String length 0 or first character is illegal (non'+'non'-' non-numeric)
        if(strs.length==0 || strs[0]!='-'&&strs[0]!='+'&&!(strs[0]>='0'&&strs[0]<='9')){
            isNum=false;
        }
        //Is an illegal number
        if(!isNum) return 0;
        //Judging positive and negative numbers
        if(strs[0]=='-') isPositive=false;
        //I means subscript from the first number, e.g.'-10', i=1; "12", i=0
        int i=(strs[0]=='-'||strs[0]=='+')?1:0;
        while(i<strs.length){//If the case is -e, +a, and so on, similar to illegal, num=0
            if(strs[i]>='0'&&strs[i]<='9'){
                num=num*10+strs[i]-'0';
                i++;
                if(num<0) break;//Overflow, return directly
                continue;
            }
            break;
        }
        if(isPositive){
            if(num<0) return Integer.MAX_VALUE;//Overflow, Maximum
            else return num;
        }else{
            if(num<0) return Integer.MIN_VALUE;//Overflow, Minimum
            else return -num;
        }
    }
}

JZ20 string representing numeric value

Title Address
describe
Implement a function to determine whether the string str represents numeric values (including scientific numbers, decimal numbers, and integers).

The numbers of scientific counting (in order) can be divided into the following parts:
1. Several spaces
2. An integer or decimal number
3. (Optional) An'e'or'E' followed by an integer (positive or negative)
4. Several spaces

Decimals (in order) can be divided into the following parts:
1. Several spaces
2. (Optional) A symbol character ('+'or'-')
3. It may be one of the following descriptive formats:
3.1 to one or fewer digits followed by a dot'.
3.2 At least one digit followed by a dot'.', followed by at least one digit
3.3 A dot'. 'followed by at least one digit
4. Several spaces

Integers (in order) can be divided into the following parts:
1. Several spaces
2. (Optional) A symbol character ('+'or'-')
3.At least one digit
4. Several spaces

For example, the strings ['+100','5e2', -123','3.1416','1E-16'] all represent values.
But ['12e','1a3.14','1.2.3','+5','12e+4.3'] are not numeric.

Tips:
1.1 <= str.length <= 25
2.str contains only English letters (upper and lower case), numbers (0-9), plus signs'+', minus signs'-', spaces', or dots'.
3. If you suspect that a use case can be represented as a numeric value, you can use python's print(float(str)) to view it
Advanced: Time Complexity 0(n), Space Complexity 0(n)

Example 1

Input:
"123.45e+6"
Return value:
true

Example 2

Input:
"1.2.3"
Return value:
false

Example 3

Input:
"."
Return value:
false

Example 4

Input:
"    .2  "
Return value:
true

Code

import java.util.*;
public class Solution {
    /**
     * The class name, method name and parameter name in the code have been specified. Do not modify them, just return to the value specified by the method. 
     * @param str string Character string 
     * @return bool Boolean
     */
    public boolean isNumeric (String str) {
        return isEnum(str);
    }
    //Determine if it is an integer
    public boolean isInt(String s){
        s=s.trim();//String space before and after
        if(s==null || s.length()==0) return false;
        if(s.length()==1&&!(s.charAt(0)>='0'&&s.charAt(0)<='9')) return false;//The string is'-'or'+'
        char[] str=s.toCharArray();
        //i denotes the subscript of the first integer in the string
        int i=(str[0]=='-' || str[0]=='+')?1:0;
        while(i<str.length){
            if(str[i]>='0' && str[i]<='9'){
                i++;
                continue;
            }
            return false;//Illegal character for non-integer
        }
        return true;
    }
    //Decimal
    public boolean isFolat(String s){
        if(s==null || s.length()==0) return false;//null
        if(s.length()==1&&!(s.charAt(0)>='0'&&s.charAt(0)<='9'||s.charAt(0)=='.')) return false;//The string is'+'or'-'
        //i denotes the subscript of the first integer in the string
        int i=(s.charAt(0)=='-' || s.charAt(0)=='+')?1:0;
        //Legal Form: (1.) (1.1) (.21)
        s=s.substring(i);//String after removing the'+'/'-'sign
        int index=s.indexOf(".");//index denotes where'. 'appears
        if(index==-1) return false;//Represents no'. '
        //If there are legitimate numbers to the left of the decimal point, the right of the decimal point can be empty or legitimate
        //Null before decimal point, legal number after decimal point
        boolean left=isInt(s.substring(0,index));//Left integer of decimal point
        boolean right=isInt(s.substring(index+1));//Integer to the right of the decimal point
        if(index!=0 && left &&(right || index==s.length()-1)){
            return true;
        }
        if(index==0 && right){
            return true;
        }
        return false;
    }
    //Is it a scientific notation
    public boolean isEnum(String s){
        if(isInt(s) || isFolat(s)) return true;//The number is an integer or decimal number
        s=s.trim();//Remove Front and Back Spaces
        //index:'e'or'E' subscript in string
        int index=(s.indexOf('e')!=-1)?s.indexOf('e'):s.indexOf('E');
        //'e'or'E' is an illegal character at the beginning or end of a string
        //Such as E123 or 123E
        if(index==0 || index==s.length()-1) return false;
        if(index==-1) return false;//Neither <integer>nor <decimal>nor <'e'or'E'> is an illegal string
        //If'e'or'E' is a decimal (or integer in decimal judgment) to the left and an integer to the right, then the string is legal
        return (isInt(s.substring(0,index)) || isFolat(s.substring(0,index))) && isInt(s.substring(index+1));
    }
}

Posted by kettle_drum on Sat, 20 Nov 2021 09:37:42 -0800