整理笔试遇见的代码题

操作字符串

字符串反转

  1. StringBuffer或StringBuilder 的 reverse 方法。

    	public String reverseStr(String str){
            StringBuffer stf = new StringBuffer();
            for (int i = 0; i < str.length(); i++) {
                stf.append(str.charAt(i));
            }
            return String.valueOf(stf.reverse());
        }
    
  2. String 的 toCharArray 方法将字符串类型转化为 Char 型数组,然后再拼接字符到一个空串中。

    	public String reverseStr(String str) {
            String rev = "";
            char[] chars = str.toCharArray();
            for (int i = chars.length - 1; i >= 0; i--) {
                rev = rev + chars[i];
            }
            return rev;
        }
    

字符串去重

  1. 创建一个空串,利用String的 charAt / indexOf / valueOf 方法进行判断

     	public String uniqueChar(String str){
            //创建一个空字符串用于接收去重后的字符串
            String s = "";
            for (int i = 0; i < str.length(); i++) {
                //获取字符串中下标为i的字符(char类型)
                char ch = str.charAt(i);
                //判断字符串第一次出现ch字符时的下标是否等于i
                if (str.indexOf(ch)==i) {
                 //将ch字符转化为String类型,并添加到字符串s的末尾
                    s = s.concat(String.valueOf(ch));
                }
            }
            return s;
        }
    
  2. StringBuffer/StringBuilder 可以直接对字符型进行拼接,省去了转换String类型的步骤

    	public String uniqueSb(String str) {
            StringBuffer stf = new StringBuffer();
            for (int i = 0; i < str.length(); i++) {
                if (str.indexOf(str.charAt(i)) == i) {
                    stf.append(str.charAt(i));
                }
            }
            return stf.toString();
        }
    
  3. 正则表达式

计算字符出现次数

  1. HashMap实现。key为字符串中的字符,value是字符的个数。遍历字符串,利用 containsKey 方法判断map中是否包含指定的键名,即判断当前字符是否存在,返回 true 则value + 1。

    public void numChar(String str) {
        HashMap<Character, Integer> map = new HashMap<>();
        for (char ch : str.toCharArray()) {
            if (map.containsKey(ch)) {
                Integer value = map.get(ch);
                value++;
                map.put(ch, value);
            } else {
                map.put(ch, 1);
            }
        }
        for (Character key : map.keySet()) {
            Integer value = map.get(key);
            System.out.println(key + "=" + value);
        }
    }
    
  2. 计算字符串中子串出现的个数,使用 replace 方法将要计算的子串替换为空串,计算子串在字符串中的长度,最后通过除法运算:子串所占长度/ 子串长度 = 子串个数。

        public static void main(String args[]) {
            String string = "112233";
            String str = "1";
            int i = string.length() - string.replace(str, "").length();
            System.out.println(i / str.length());
        }
    

集合

返回数组中和为目标数的下标

 /*
 	给定一个数组,输入一个目标值,返回数组中和为目标值的两个数的下标。
 */
public int[] targetNum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        int[] arr = new int[2];
        for (int i = 0; i < nums.length; i++) {
            int k = target - nums[i];
            if (map.containsKey(nums[i])) {
                arr[0] = map.get(nums[i]);
                arr[1] = i;
                break;
            }
            map.put(k, i);
        }
        return arr;
    }

I/O流

以字节流方式写入文件

    //在当前目录下创建一个test.txt文件,写入“Hello World”,如果文件存在,则追加到末尾
    @Test
    public void fileTest2() throws IOException {
        FileOutputStream fos = new FileOutputStream("test.txt", true);
        FileInputStream fis = new FileInputStream("test.txt");

        String s = "Hello World";
        try {
            fos.write(s.getBytes());
            byte[] buf = new byte[1024];
            int length = 0;
            while ((length = fis.read(buf)) != -1) {
                System.out.println("长度" + length);
                System.out.println(new String(buf, 0, length));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            fis.close();
            fos.close();
        }
    }

使用字符流复制txt文件

//  生成当前目录下Demo.txt文件的Copy副本
    @Test
    public void fileTest4() throws IOException {
        FileReader fr = new FileReader("Demo.txt");
        FileWriter fw = new FileWriter("Demo_Copy.txt");
        try {
            char[] c = new char[1024];
            int len = 0;
            while ((len = fr.read(c)) != -1) {
                fw.write(c, 0, len);
                fw.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            fw.close();
            fr.close();
        }
    }

多线程

获取硬盘大小

/**
 * 有4个线程分别获取C、D、E、F盘的大小,第5个线程统计总大小
 */
public class MyCode {
 
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(4);
        DiskMemory diskMemory = new DiskMemory();
        CountDownLatch countDownLatch = new CountDownLatch(4);
        for (int i = 0; i < 4; i++) {
            executorService.execute(() -> {
                try {
                    int size = diskMemory.getSize();
                    diskMemory.setSize(size);
                    Thread.sleep(1000);
                    System.out.println("线程执行,磁盘大小:" + size);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                countDownLatch.countDown();
                System.out.println("--------");
            });
        }
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("磁盘总大小:" + diskMemory.getTotalSize());
        //线程池使用完需要手动关闭
        executorService.shutdown();
    }
}
 
public class DiskMemory {
 
    private int totalSize;
 
    public int getSize() {
        return (new Random().nextInt(3) + 1) * 100; //加一是为了防止获取磁盘大小为0,不符合常理
    }
 
    public void setSize(int size) {
        totalSize += size;
    }
 
    public int getTotalSize() {
        return totalSize;
    }
}
posted @ 2021-07-28 09:12  Leejk  阅读(45)  评论(0编辑  收藏  举报