CodeTop算法(3.4-3.5)

136 阅读6分钟

1 IP地址合法性检验

package day0303;


import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Scanner;

/**
 * @author mk
 * @description
 * @create 2022-03-2022/3/3 21:39
 */
public class IPjudge {
    public static void main(String[] args) {
        Scanner str = new Scanner(System.in);
        System.out.println("请输入要检查的IP地址:");
        String b = str.nextLine();
        if (IPjudge.ipCheck(b)) {
            System.out.println("正确");
        }else {
            System.out.println("错误");
        }
        IPjudge.main(args);
    }

    public static boolean ipCheck(String text) {
        if (text != null && !text.isEmpty()) {
            // 定义正则表达式
            String regex = "^(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[1-9])\."
                    + "(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\." + "(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\."
                    + "(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)$";
            // 判断ip地址是否与正则表达式匹配
            if (text.matches(regex)) {
                // 返回判断信息
                return true;
            } else {
                // 返回判断信息
                return false;
            }
        }
        return false;
    }

    private static boolean testIP(String name){
        try {
            InetAddress inetaddr=InetAddress.getByName(name);
        } catch (UnknownHostException e) {
            return false;
        }
        return true;
    }
}

2 文件读取和写入

package javaIO;

import org.junit.Test;

import java.io.*;

/**
 * 一、流的分类:
 * 1.操作数据单位:字节流、字符流
 * 2.数据的流向:输入流、输出流
 * 3.流的角色:节点流、处理流
 *
 * 二、流的体系结构
 * 抽象基类         节点流(或文件流)                               缓冲流(处理流的一种)
 * InputStream     FileInputStream   (read(byte[] buffer))        BufferedInputStream (read(byte[] buffer))
 * OutputStream    FileOutputStream  (write(byte[] buffer,0,len)  BufferedOutputStream (write(byte[] buffer,0,len) / flush()
 * Reader          FileReader (read(char[] cbuf))                 BufferedReader (read(char[] cbuf) / readLine())
 * Writer          FileWriter (write(char[] cbuf,0,len)           BufferedWriter (write(char[] cbuf,0,len) / flush()
 *
 * @author mk
 * @description
 * @create 2022-02-2022/2/27 21:10
 */
public class FileReaderWriterTest {

    public static void main(String[] args) {
        File file = new File("hello.txt");//相较于当前工程
        System.out.println(file.getAbsolutePath());

        File file1 = new File("day08\hello.txt");
        System.out.println(file1.getAbsolutePath());
    }

    /*
    将day09下的hello.txt文件内容读入程序中,并输出到控制台

    说明点:
    1. read()的理解:返回读入的一个字符。如果达到文件末尾,返回-1
    2. 异常的处理:为了保证流资源一定可以执行关闭操作。需要使用try-catch-finally处理
    3. 读入的文件一定要存在,否则就会报FileNotFoundException。

     */

    @Test
    public void testFileReader(){
        FileReader fr = null;

        try {
            //1.实例化File类的对象,指明要操作的文件
            File file = new File("hello.txt");//相较于当前Module
            //2.提供具体的流
            fr = new FileReader(file);
            //3.数据的读入
//        int data = fr.read();
//        //read():返回读入的一个字符。如果达到文件末尾,返回-1
//        while(data != -1){
//            System.out.print((char)data);
//            data = fr.read();
//        }
            //方式二:语法上针对于方式一的修改
            int data;
            while((data = fr.read()) != -1){
                System.out.print((char)data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fr != null) {
                //4.流的关闭操作
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }


    //对read()操作升级:使用read的重载方法
    @Test
    public void testFileReader1()  {
        FileReader fr = null;
        try {
            //1.File类的实例化
            File file = new File("hello.txt");

            //2.FileReader流的实例化
            fr = new FileReader(file);

            //3.读入的操作
            //read(char[] cbuf):返回每次读入cbuf数组中的字符的个数。如果达到文件末尾,返回-1
            char[] cbuf = new char[5];
            int len;
            while((len = fr.read(cbuf)) != -1){
                //方式一:
                //错误的写法
//                for(int i = 0;i < cbuf.length;i++){
//                    System.out.print(cbuf[i]);
//                }
                //正确的写法
//                for(int i = 0;i < len;i++){
//                    System.out.print(cbuf[i]);
//                }
                //方式二:
                //错误的写法,对应着方式一的错误的写法
//                String str = new String(cbuf);
//                System.out.print(str);
                //正确的写法
                String str = new String(cbuf,0,len);
                System.out.print(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fr != null){
                //4.资源的关闭
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }

    }


    /*
        从内存中写出数据到硬盘的文件里。

        说明:
        1. 输出操作,对应的File可以不存在的。并不会报异常
        2.
             File对应的硬盘中的文件如果不存在,在输出的过程中,会自动创建此文件。
             File对应的硬盘中的文件如果存在:
                    如果流使用的构造器是:FileWriter(file,false) / FileWriter(file):对原有文件的覆盖
                    如果流使用的构造器是:FileWriter(file,true):不会对原有文件覆盖,而是在原有文件基础上追加内容

         */
    @Test
    public void testFileWriter() {
        FileWriter fw = null;
        try {
            //1.提供File类的对象,指明写出到的文件
            File file = new File("hello1.txt");

            //2.提供FileWriter的对象,用于数据的写出
            fw = new FileWriter(file,false);

            //3.写出的操作
            fw.write("I have a dream!\n");
            fw.write("you need to have a dream!");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.流资源的关闭
            if(fw != null){

                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }


    @Test
    public void testFileReaderFileWriter() throws IOException {
        FileReader fr = null;
        FileWriter fw = null;
        try {
            //1.创建File类的对象,指明读入和写出的文件
            File srcFile = new File("hello.txt");
            File destFile = new File("hello2.txt");
            //不能使用字符流来处理图片等字节数据
//            File srcFile = new File("爱情与友情.jpg");
//            File destFile = new File("爱情与友情copy.jpg");


            //2.创建输入流和输出流的对象
            fr = new FileReader(srcFile);
            fw = new FileWriter(destFile);

            //3.数据的读入和写出操作
            char[] cbuf = new char[5];
            int len;
            while((len = fr.read(cbuf))!= -1){
                fw.write(cbuf,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.关闭
            try {
                if(fw != null){fw.close();}

            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(fr != null){fr.close();}
            } catch (IOException e) {
                e.printStackTrace();
            }

        }


    }
}
package javaIO;

import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 测试FileInputStream和FileOutputStream的使用
 *  *
 *  * 结论:
 *  * 1. 对于文本文件(.txt,.java,.c,.cpp),使用字符流处理
 *  * 2. 对于非文本文件(.jpg,.mp3,.mp4,.avi,.doc,.ppt,...),使用字节流处理
 *  *
 * @author mk
 * @description
 * @create 2022-02-2022/2/28 11:24
 */
public class FileInputOutputStreamTest {

    //使用字节流FileInputStream处理文本文件,中文可能出现乱码。
    @Test
    public void testFileInputStream() {
        FileInputStream fis = null;
        try {
            //1. 造文件
            File file = new File("hello.txt");

            //2.造流
            fis = new FileInputStream(file);

            //3.读数据
            byte[] buffer = new byte[5];
            int len;//记录每次读取的字节的个数
            while((len = fis.read(buffer)) != -1){

                String str = new String(buffer,0,len);
                System.out.print(str);

            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fis != null){
                //4.关闭资源
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }

    }


    /*
    实现对图片的复制操作
     */
    @Test
    public void testFileInputOutputStream()  {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            //
            File srcFile = new File("1188.jpg");
            File destFile = new File("118899.jpg");

            //
            fis = new FileInputStream(srcFile);
            fos = new FileOutputStream(destFile);

            //复制的过程
            byte[] buffer = new byte[5];
            int len;
            while((len = fis.read(buffer)) != -1){
                fos.write(buffer,0,len);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fos != null){
                //
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }

    }



    //指定路径下文件的复制
    public void copyFile(String srcPath,String destPath){
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            //
            File srcFile = new File(srcPath);
            File destFile = new File(destPath);

            //
            fis = new FileInputStream(srcFile);
            fos = new FileOutputStream(destFile);

            //复制的过程
            byte[] buffer = new byte[1024];
            int len;
            while((len = fis.read(buffer)) != -1){
                fos.write(buffer,0,len);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fos != null){
                //
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }


    }


    @Test
    public void testCopyFile(){

        long start = System.currentTimeMillis();

        String srcPath = "E:\MK-pc\always\深度学习框架PyTorch000.pdf";
        String destPath = "E:\MK-pc\always\深度学习框架PyTorch111.pdf";


//        String srcPath = "hello.txt";
//        String destPath = "hello3.txt";

        copyFile(srcPath,destPath);


        long end = System.currentTimeMillis();

        System.out.println("复制操作花费的时间为:" + (end - start));//1008

    }


}

3 剑指 Offer 46. 把数字翻译成字符串

给定一个数字,我们按照如下规则把它翻译为字符串:0 翻译成 “a” ,1 翻译成 “b”,……,11 翻译成 “l”,……,25 翻译成 “z”。一个数字可能有多个翻译。请编程实现一个函数,用来计算一个数字有多少种不同的翻译方法。

输入: 12258
输出: 5
解释: 122585种不同的翻译,分别是"bccfi", "bwfi", "bczi", "mcfi""mzi"
package day0304;

/**
 * @author mk
 * @description
 * 给定一个数字,我们按照如下规则把它翻译为字符串:
 * 0 翻译成 “a” ,1 翻译成 “b”,……,11 翻译成 “l”,……,25 翻译成 “z”。
 * 一个数字可能有多个翻译。
 *
 * 请编程实现一个函数,用来计算一个数字有多少种不同的翻译方法。
 *
 * 输入: 12258
 * 输出: 5
 * 解释: 12258有5种不同的翻译,分别是"bccfi", "bwfi", "bczi", "mcfi"和"mzi"
 *
 * @create 2022-03-2022/3/4 11:21
 */
public class TranslateNum {
    public static void main(String[] args) {
        int num = 12258;
        String s = String.valueOf(num);
        int a = 1, b = 1;
        for(int i = 2; i <= s.length(); i++) {
            String tmp = s.substring(i - 2, i);
            int c = tmp.compareTo("10") >= 0 && tmp.compareTo("25") <= 0 ? a + b : a;
            b = a;
            a = c;
        }
        System.out.println(a);
//        return r;
    }
    public int translateNum(int num) {
        int a = 1, b = 1, x, y = num % 10;
        while(num != 0) {
            num /= 10;
            x = num % 10;
            int tmp = 10 * x + y;
            int c = (tmp >= 10 && tmp <= 25) ? a + b : a;
            b = a;
            a = c;
            y = x;
        }
        return a;
    }


}
class Solution {
    public int translateNum(int num) {
        if(num == 0){return 1;}  //只有一个a
        return deep(num);
    }
    public int deep(int num){
        if(num<10){return 1;}  //只有一个字母,找到一种
        if(num%100 <= 25 && num%100 >=10){
            //证明两个余数可以组成一个字母,并且余数不是以0开头,因为余数大于等于10,表明下次可以选俩数字也可以选一个数字
            return deep(num/100) + deep(num/10);
        }
        else{
            return deep(num/10);   //不满足上述条件证明两个数字是以0开头的,只能选一个数字。
        }
    }
}
package day0304;

/**
 * @author mk
 * @description
 * 给定一个数字,我们按照如下规则把它翻译为字符串:
 * 0 翻译成 “a” ,1 翻译成 “b”,……,11 翻译成 “l”,……,25 翻译成 “z”。
 * 一个数字可能有多个翻译。
 *
 * 请编程实现一个函数,用来计算一个数字有多少种不同的翻译方法。
 *
 * 输入: 12258
 * 输出: 5
 * 解释: 12258有5种不同的翻译,分别是"bccfi", "bwfi", "bczi", "mcfi"和"mzi"
 *
 * @create 2022-03-2022/3/4 11:21
 */
public class TranslateNum1 {

    public static void main(String[] args) {
        int number = 12258;
        TranslateNum1 t = new TranslateNum1();
        System.out.println(t.translateNum(number));;
    }
    public int translateNum(int num) {
        if(num == 0){return 1;}  //只有一个a
        return deep(num);
    }
    public int deep(int num){
        if(num<10){return 1;}  //只有一个字母,找到一种
        if(num%100 <= 25 && num%100 >=10){
            //证明两个余数可以组成一个字母,并且余数不是以0开头,因为余数大于等于10,表明下次可以选俩数字也可以选一个数字
            return deep(num/100) + deep(num/10);
        }
        else{
            return deep(num/10);   //不满足上述条件证明两个数字是以0开头的,只能选一个数字。
        }
    }
}

4 剑指 Offer 04. 二维数组中的查找

在一个 n * m 的二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个高效的函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。

示例:
现有矩阵 matrix 如下:
[
  [1,   4,  7, 11, 15],
  [2,   5,  8, 12, 19],
  [3,   6,  9, 16, 22],
  [10, 13, 14, 17, 24],
  [18, 21, 23, 26, 30]
]
给定 target = 5,返回 true。
给定 target = 20,返回 false
class Solution {
    public boolean findNumberIn2DArray(int[][] matrix, int target) {
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
            return false;
        }
        int hang = matrix.length;
        int lie =matrix[0].length;
        // for(int i = 0;i < hang ;i++){
        //     for(int j = 0;j < lie ;j++){
        //         if(matrix[i][j]==target){
        //             return true;
        //         }
        //     }
        // }
        int h = 0;
        int l = lie - 1;
        while(h < hang && l >= 0){
            int num = matrix[h][l];
            if(num == target){
                return true;
            }else if(num > target){
                l--;
            }else{
                h++;
            }

        }
        return false;
    }
}

5 最长特殊序列 Ⅰ

给你两个字符串 a 和 b,请返回 这两个字符串中 最长的特殊序列  的长度。如果不存在,则返回 -1 。

「最长特殊序列」 定义如下:该序列为 某字符串独有的最长子序列(即不能是其他字符串的子序列) 。

字符串 s 的子序列是在从 s 中删除任意数量的字符后可以获得的字符串。

例如,"abc" 是 "aebdc" 的子序列,因为删除 "aebdc" 中斜体加粗的字符可以得到 "abc" 。 "aebdc" 的子序列还包括 "aebdc" 、 "aeb" 和 "" (空字符串)。  

示例 1:

输入: a = "aba", b = "cdc"
输出: 3
解释: 最长特殊序列可为 "aba" (或 "cdc"),两者均为自身的子序列且不是对方的子序列。
示例 2:

输入:a = "aaa", b = "bbb"
输出:3
解释: 最长特殊序列是 "aaa""bbb" 。
示例 3:

输入:a = "aaa", b = "aaa"
输出:-1
解释: 字符串 a 的每个子序列也是字符串 b 的每个子序列。同样,字符串 b 的每个子序列也是字符串 a 的子序列。
class Solution {
    public int findLUSlength(String a, String b) {
        return !a.equals(b) ? Math.max(a.length(), b.length()) : -1;
    }
}

字符串的子序列的长度不会超过该字符串的长度。若子序列的长度等于字符串的长度,那么子序列就是该字符串。

两字符串不相同,那么我们可以选择较长的字符串作为最长特殊序列,显然它不会是较短的字符串的子序列。特别地,当两字符串长度相同时(但不是同一字符串),我们仍然可以选择其中的一个字符串作为最长特殊序列,它不会是另一个字符串的子序列。

若两字符串相同,那么任一字符串的子序列均会出现在两个字符串中,此时应返回 −1。

6 替换空格。请实现一个函数,把字符串 s 中的每个空格替换成"%20"。

输入: s = "We are happy."
输出: "We%20are%20happy."
class Solution {
    public String replaceSpace(String s) {
        // return s.replace(" ","%20");

        int size = 0;
        char[] newchar = new char[s.length()*3];
        for(int i = 0;i < s.length();i++){        
            if(s.charAt(i) == ' '){
                newchar[size++] = '%';
                newchar[size++] = '2';
                newchar[size++] = '0';
            }else{
                   newchar[size++] = s.charAt(i);
            }
        }
        String newstr = new String(newchar,0,size);
        return newstr;
    }
}