常见Java面试编程题(牛客整理)

1、怎么检查一个字符串只包含数字?解决方案

(1)采用正则表达式匹配,循环匹配

如果匹配的不是数字就返回false,如果是就返回true

    public boolean checkNumber(String str) {
        Pattern compile = Pattern.compile("[^\\d]");
        Matcher matcher = compile.matcher(str);

        while (matcher.find()) {
            return false;
        }
        return true;
    }

(2)采用正则表达式,直接匹配

    public boolean checkNumber2(String str) {
        return str.matches("^[\\d]+$");
    }

(3)for循环匹配

public boolean checkNumber3(String str) {
        char[] chars = str.toCharArray();
        int length = str.length();

        for (int i = 0; i < length; i++) {
            char c = str.charAt(i);
            if (!Character.isDigit(c)) {
                return false;
            }
        }
        return true;
    }

(4)ascii码判断

48~57为0到9十个阿拉伯数字: ‘0’~‘9’
65~90为26个大写英文字母 :‘A’~‘Z’
97~122号为26个小写英文字母:‘a’~‘z’

public boolean checkNumber4(String str) {
        char[] chars = str.toCharArray();
        int length = str.length();

        for (int i = 0; i < length; i++) {
            char c = str.charAt(i);
            if (c < 48 || c > 57) {
                return false;
            }
        }
        return true;

    }

2、Java 中如何利用泛型写一个 LRU 缓存?

(1):继承LinkedHashMap

package com.newcode;

import org.junit.Test;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author wty
 * @date 2023/3/10 14:05
 */
public class Exercise03 {
    @Test
    public void test() {
        LRUCacheExercise<Integer, Integer> lruMap = new LRUCacheExercise<Integer, Integer>(16);

        for (int i = 0; i < 20; i++) {
            lruMap.put(i, i);
        }

        Set<Map.Entry<Integer, Integer>> entries = lruMap.entrySet();
        for (Map.Entry<Integer, Integer> entry : entries) {
            System.out.println("key:" + entry.getKey() + " value:" + entry.getValue());
        }

    }
}

class LRUCacheExercise<K, V> extends LinkedHashMap<K, V> {
    private int capacity;

    public LRUCacheExercise(int capacity) {
        super(capacity, 0.75f, true);
        this.capacity = capacity;
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        return size() > capacity;
    }
}

输出结果:

key:4 value:4
key:5 value:5
key:6 value:6
key:7 value:7
key:8 value:8
key:9 value:9
key:10 value:10
key:11 value:11
key:12 value:12
key:13 value:13
key:14 value:14
key:15 value:15
key:16 value:16
key:17 value:17
key:18 value:18
key:19 value:19

(2)手写一个类

package com.newcode;

import org.junit.Test;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author wty
 * @date 2023/3/10 14:05
 */
public class Exercise03 {
    @Test
    public void test() {
        LRUCacheExercise<Integer, Integer> lruMap = new LRUCacheExercise<Integer, Integer>(16);

        for (int i = 0; i < 20; i++) {
            lruMap.put(i, i);
        }

        Set<Map.Entry<Integer, Integer>> entries = lruMap.entrySet();
        for (Map.Entry<Integer, Integer> entry : entries) {
            System.out.println("key:" + entry.getKey() + " value:" + entry.getValue());
        }

    }
}

class LRUCacheExercise<K, V> extends LinkedHashMap<K, V> {
    private int capacity;

    public LRUCacheExercise(int capacity) {
        super(capacity, 0.75f, true);
        this.capacity = capacity;
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        return size() > capacity;
    }
}

输出结果

{19=19,18=18,17=17,16=16,15=15,14=14,13=13,12=12,11=11,10=10,9=9,8=8,7=7,6=6,5=5,4=4}

3、写一段 Java 程序将 byte 转换为 long?

package com.newcode;

import org.junit.Test;

import java.nio.Buffer;
import java.nio.ByteBuffer;

/**
 * @author wty
 * @date 2023/3/10 19:07
 */
public class Exercise07 {
    @Test
    public void test() {
        long a = 23456L;
        byte[] bytes = longtoBytes(a);
        System.out.println(bytes);

        long l = bytesToLong(bytes);
        System.out.println(l);
    }

    private ByteBuffer byteBuffer = ByteBuffer.allocate(8);

    // long转换为bytes数组
    public byte[] longtoBytes(long l) {
        byteBuffer.putLong(0, l);
        return byteBuffer.array();
    }

    // bytes数组转换为long
    public long bytesToLong(byte[] a) {
        byteBuffer.put(a, 0, a.length);
        byteBuffer.flip();
        return byteBuffer.getLong();
    }
}

输出结果

[B@117ae12
23456

4、在不使用 StringBuffer 的前提下,怎么反转一个字符串?

见链接
字符串反转

5、Java 中,怎么获取一个文件中单词出现的最高频率?

package com.newcode;

import org.junit.Test;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;

/**
 * @author wty
 * @date 2023/3/10 21:56
 */
public class Exercise12 {
    @Test
    public void test() {
        System.out.println(calMoreSubStringsinFile());
    }

    public String calMoreSubStringsinFile() {
        String path = "D:\\1.txt";
        BufferedReader bufferedReader = null;
        StringBuilder sb = new StringBuilder();
        try {
            bufferedReader = new BufferedReader(new FileReader(path));
            String strRead = "";
            while ((strRead = bufferedReader.readLine()) != null) {
                sb.append(strRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return maxCount(sb.toString());
    }

    public String maxCount(String str) {
        str = str.replace(",", " ");
        str = str.replace(".", " ");
        str = str.replace("!", " ");
        String[] arrStr = str.split("\\s+");
        int length = arrStr.length;

        HashMap<String, Integer> map = new HashMap<>();

        for (int i = 0; i < length; i++) {
            String sub = arrStr[i];
            map.put(sub, map.getOrDefault(sub, 0) + 1);
        }

        Set<Map.Entry<String, Integer>> entries = map.entrySet();
        int max = 0;
        String sub = "";
        for (Map.Entry<String, Integer> entry : entries) {
            int count = entry.getValue();
            if (count > max) {
                sub = entry.getKey();
                max = count;
            }
        }
        return sub;
    }
}

其中文档中是

today is Sunday,I go to shop. I am very happy because today is Weekend.I like Sunday.

最后控制台输出

I

6、如何检查出两个给定的字符串是反序的?

package com.newcode;

import org.junit.Test;

/**
 * @author wty
 * @date 2023/3/10 22:40
 */
public class Exercise13 {
    @Test
    public void test() {
        String str1 = "abcd";
        String str2 = "dcba";
        System.out.println(isReverse(str1, str2));
    }

    public boolean isReverse(String str1, String str2) {
        int length1 = str1.length();
        int length2 = str2.length();
        if (length1 != length2) {
            return false;
        }

        for (int i = 0; i < length1; i++) {
            if (str1.charAt(i) != str2.charAt(length2 - i - 1)) {
                return false;
            }
        }
        return true;
    }
}

输出

true

7、Java 中,怎么打印出一个字符串的所有排列?

package com.newcode;

import org.junit.Test;

import java.util.Scanner;

/**
 * @author wty
 * @date 2023/3/10 23:12
 */
public class Exercise17 {
    @Test
    public void test() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入字符串");
        String str = scanner.nextLine();
        printPermutations(str, 0, str.length());
    }


    /**
     * 辅助函数,用于交换字符串中的两个字符
     */
    public static String swap(String str, int i, int j) {
        char[] chars = str.toCharArray();
        char temp = chars[i];
        chars[i] = chars[j];
        chars[j] = temp;
        return String.valueOf(chars);
    }

    /**
     * 主函数,用于打印出一个字符串的所有排列
     */

    public static void printPermutations(String str, int start, int end) {
        // 基本情况:如果只有一个字符,直接打印
        if (start == end - 1) {
            System.out.println(str);
        } else {
            // 递归情况:对于每个可能的位置,将其与第一个字符交换,并递归地处理剩余的子字符串
            for (int i = start; i < end; i++) {
                // 交换第一个字符和当前位置的字符
                str = swap(str, start, i);
                // 递归地处理剩余的子字符串
                printPermutations(str, start + 1, end);
                // 恢复原始字符串
                str = swap(str, start, i);
            }
        }
    }
}

8、Java 中,怎样才能打印出数组中的重复元素?

package com.newcode;

import org.junit.Test;

/**
 * @author wty
 * @date 2023/3/10 23:22
 */
public class Exercise18 {
    @Test
    public void test() {
        int nums[] = {1, 2, 2, 3, 3, 3, 4, 5, 6, 6, 7};
        repeatedNum(nums);
    }

    public void repeatedNum(int nums[]) {
        int length = nums.length;

        for (int i = 0; i < length - 1; i++) {
            for (int j = i + 1; j < length; j++) {
                if (nums[i] == nums[j]) {
                    System.out.println("重复元素:" + nums[j]);
                }
            }
        }
    }
}

输出结果

重复元素:2
重复元素:3
重复元素:3
重复元素:3
重复元素:6

9、Java 中如何将字符串转换为整数?

package com.newcode;

import org.junit.Test;

/**
 * @author wty
 * @date 2023/3/10 23:27
 */
public class Exercise19 {
    @Test
    public void test() {
        String a = "4399";

        long start = System.currentTimeMillis();
        for (int t = 0; t < 80000000; t++) {
            int i = Integer.parseInt(a);
        }
        //System.out.println(i);
        long end = System.currentTimeMillis();
        System.out.println("Integer.parseInt总耗时为:" + (end - start));


        String b = "8360";
        long start2 = System.currentTimeMillis();
        for (int t = 0; t < 80000000; t++) {
            Integer i2 = Integer.valueOf(b);
        }

        long end2 = System.currentTimeMillis();
        System.out.println("Integer.valueOf总耗时为:" + (end2 - start2));

        //System.out.println(i2);
    }
}

输出结果

Integer.parseInt总耗时为:4001
Integer.valueOf总耗时为:4541

可以发现parseInt性能好,原因是:
valueOf中嵌套了parseInt,多了内层方法的调用
在这里插入图片描述

10、在没有使用临时变量的情况如何交换两个整数变量的值?

package com.newcode;

import org.junit.Test;

/**
 * @author wty
 * @date 2023/3/10 23:27
 */
public class Exercise20 {
    @Test
    public void test() {
        int a = 20;
        int b = 10;

        a = a ^ b;
        b = a ^ b;
        a = a ^ b;

        System.out.println("a:" + a);
        System.out.println("b:" + b);
    }
}

输出

a:10
b:20
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

心向阳光的天域

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值