总结一下用Java做算法的常用类和方法

1. 数组操作 (Arrays)

  • Arrays.sort(array): 排序
  • Arrays.binarySearch(array, key): 二分查找
  • Arrays.fill(array, value): 填充值
  • Arrays.copyOf(array, newLength): 复制数组
  • Arrays.toString(array): 转换为字符串

2. 集合类 (Collection, List, Set, Map)

  • List (ArrayList) :
    • add(element), get(index), size(), contains(element), indexOf(element)
  • Set (HashSet) :
    • add(element), remove(element), contains(element), size()
  • Map (HashMap) :
    • put(key, value), get(key), containsKey(key), containsValue(value), size(), keySet(), values()

3. 字符串操作 (String)

  • length(), charAt(index), substring(start, end), startsWith(prefix), endsWith(suffix)
  • replace(old, new), toUpperCase(), toLowerCase(), trim(), split(regex)
  • StringBuilder 用于频繁拼接(第8点会详细讲)

4. 数学运算 (Math)

  • Math.max(a, b), Math.min(a, b), Math.abs(x), Math.sqrt(x), Math.pow(base, exp), Math.random()

5. 输入输出 (Scanner, BufferedReader)

  • Scanner: nextInt(), nextLine(), hasNext(), hasNextInt()
  • BufferedReader: readLine()

6. 排序和查找 (Collections)

  • Collections.sort(list), Collections.reverseOrder()
  • Collections.max(collection), Collections.min(collection)
  • Collections.binarySearch(list, key)

7. 数据结构

  • Stack : Deque<Integer> stack = new ArrayDeque<>(), push(), pop(), peek()
  • Queue : Queue<Integer> queue = new LinkedList<>(), offer(), poll(), peek()
  • PriorityQueue : 默认最小堆,offer(), poll(), peek()
  • Deque : ArrayDeque<>, 支持两端操作

8. StringBuilder (高效字符串操作):StringBuilder用于大量字符串拼接

  • append(): 追加字符串
  • insert(): 插入字符串
  • delete(): 删除字符
  • replace(): 替换字符
  • reverse(): 反转字符串
  • length(): 获取长度
  • toString(): 转换为String

9.正则表达式 (Pattern/Matcher):正则表达式用于模式匹配

  • Pattern.compile(pattern): 编译正则模式
  • matcher.find(): 查找匹配项
  • matcher.group(): 获取匹配的内容
  • String.split(regex): 按正则分割
  • String.replaceAll(regex, replacement): 正则替换
  • String.matches(regex): 完全匹配

10. 其他实用类

  • Integer.parseInt(string), Double.parseDouble(string)
  • String.valueOf(number)
  • System.currentTimeMillis() (计时)
java 复制代码
import java.util.*;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

/**
 * Java算法常用类和方法总结
 */
public class AlgorithmUtilsSummaryComplete {
    
    public static void main(String[] args) {
        System.out.println("=== Java算法常用类和方法总结 - 完整版 ===\n");
        
        // 1. StringBuilder操作
        demonstrateStringBuilderOperations();
        
        // 2. 正则表达式
        demonstrateRegexOperations();
        
        // 3. 数组操作
        demonstrateArrayOperations();
        
        // 4. 集合类操作
        demonstrateCollectionOperations();
        
        // 5. 字符串操作
        demonstrateStringOperations();
        
        // 6. 数学运算
        demonstrateMathOperations();
        
        // 7. 输入输出
        demonstrateIOOperations();
        
        // 8. 排序
        demonstrateSorting();
        
        // 9. 查找
        demonstrateSearching();
        
        // 10. 数据结构
        demonstrateDataStructures();
    }
    
    // 1. StringBuilder操作
    public static void demonstrateStringBuilderOperations() {
        System.out.println("1. StringBuilder操作:");
        StringBuilder sb = new StringBuilder();
        
        // append: 追加
        sb.append("Hello");
        sb.append(" ");
        sb.append("World");
        System.out.println("追加后: " + sb.toString());
        
        // insert: 插入
        sb.insert(5, "_Java_");
        System.out.println("插入后: " + sb.toString());
        
        // delete: 删除
        sb.delete(5, 11); // 删除索引5到10的字符
        System.out.println("删除后: " + sb.toString());
        
        // replace: 替换
        sb.replace(0, 5, "Hi");
        System.out.println("替换后: " + sb.toString());
        
        // reverse: 反转
        sb.reverse();
        System.out.println("反转后: " + sb.toString());
        
        // length: 长度
        System.out.println("长度: " + sb.length());
        
        // capacity: 容量
        System.out.println("容量: " + sb.capacity());
        
        // charAt: 获取字符
        System.out.println("索引0的字符: " + sb.charAt(0));
        
        // substring: 子字符串
        System.out.println("子字符串: " + sb.substring(0, 2));
        
        // setCharAt: 设置字符
        sb.setCharAt(0, 'h');
        System.out.println("设置字符后: " + sb.toString());
        
        System.out.println();
    }
    
    // 2. 正则表达式
    public static void demonstrateRegexOperations() {
        System.out.println("2. 正则表达式操作:");
        
        // Pattern和Matcher
        String text = "我的电话是138-1234-5678,邮箱是user@example.com,身份证号是123456789012345678";
        
        // 匹配手机号
        String phonePattern = "\\d{3}-\\d{4}-\\d{4}";
        Pattern phoneRegex = Pattern.compile(phonePattern);
        Matcher phoneMatcher = phoneRegex.matcher(text);
        
        System.out.println("匹配手机号:");
        while (phoneMatcher.find()) {
            System.out.println("找到手机号: " + phoneMatcher.group());
        }
        
        // 匹配邮箱
        String emailPattern = "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}";
        Pattern emailRegex = Pattern.compile(emailPattern);
        Matcher emailMatcher = emailRegex.matcher(text);
        
        System.out.println("匹配邮箱:");
        while (emailMatcher.find()) {
            System.out.println("找到邮箱: " + emailMatcher.group());
        }
        
        // 匹配身份证号
        String idPattern = "\\d{17}[\\dXx]";
        Pattern idRegex = Pattern.compile(idPattern);
        Matcher idMatcher = idRegex.matcher(text);
        
        System.out.println("匹配身份证:");
        while (idMatcher.find()) {
            System.out.println("找到身份证: " + idMatcher.group());
        }
        
        // 字符串的正则方法
        String sentence = "hello world 123 java 456";
        
        // split: 分割
        String[] parts = sentence.split("\\s+"); // 按空格分割
        System.out.println("分割结果: " + Arrays.toString(parts));
        
        // replaceAll: 替换所有匹配项
        String replaced = sentence.replaceAll("\\d+", "NUM"); // 将数字替换为NUM
        System.out.println("替换数字后: " + replaced);
        
        // replaceFirst: 替换第一个匹配项
        String replacedFirst = sentence.replaceAll("\\d+", "NUMBER");
        System.out.println("替换所有数字后: " + replacedFirst);
        
        // matches: 完全匹配
        String number = "12345";
        boolean isNumber = number.matches("\\d+");
        System.out.println("字符串'" + number + "'是否为纯数字: " + isNumber);
        
        // 常用正则模式
        System.out.println("\n常用正则模式:");
        System.out.println("- 数字: \\d+");
        System.out.println("- 字母: [a-zA-Z]+");
        System.out.println("- 字母数字: [a-zA-Z0-9]+");
        System.out.println("- 空白字符: \\s+");
        System.out.println("- 非空白字符: \\S+");
        System.out.println("- 任意字符: .*");
        System.out.println("- IP地址: ((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)");
        System.out.println("- URL: https?://[\\w.-]+(?:\\.[\\w\\.-]+)+[/\\w\\.-]*");
        
        System.out.println();
    }
    
    // 3. 数组操作
    public static void demonstrateArrayOperations() {
        System.out.println("3. 数组操作:");
        int[] arr = {3, 1, 4, 1, 5, 9, 2, 6};
        
        // 排序
        Arrays.sort(arr);
        System.out.println("排序后: " + Arrays.toString(arr));
        
        // 二分查找
        int index = Arrays.binarySearch(arr, 5);
        System.out.println("查找5的位置: " + index);
        
        // 填充
        int[] fillArr = new int[5];
        Arrays.fill(fillArr, 1);
        System.out.println("填充数组: " + Arrays.toString(fillArr));
        
        // 复制
        int[] copyArr = Arrays.copyOf(arr, arr.length);
        System.out.println("复制数组: " + Arrays.toString(copyArr));
        
        // 比较
        int[] arr2 = {1, 2, 3, 4, 5, 6, 9, 9};
        System.out.println("数组比较: " + Arrays.equals(arr, arr2));
        
        System.out.println();
    }
    
    // 4. 集合类操作
    public static void demonstrateCollectionOperations() {
        System.out.println("4. 集合类操作:");
        
        // List
        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(1);
        System.out.println("List: " + list);
        System.out.println("List大小: " + list.size());
        System.out.println("是否包含1: " + list.contains(1));
        System.out.println("第一次出现1的位置: " + list.indexOf(1));
        System.out.println("最后一次出现1的位置: " + list.lastIndexOf(1));
        
        // Set
        Set<Integer> set = new HashSet<>();
        set.add(1);
        set.add(2);
        set.add(3);
        set.add(1); // 重复元素会被忽略
        System.out.println("Set: " + set);
        System.out.println("Set大小: " + set.size());
        System.out.println("Set是否包含2: " + set.contains(2));
        
        // Map
        Map<String, Integer> map = new HashMap<>();
        map.put("one", 1);
        map.put("two", 2);
        map.put("three", 3);
        System.out.println("Map: " + map);
        System.out.println("Map大小: " + map.size());
        System.out.println("key 'two'对应的值: " + map.get("two"));
        System.out.println("Map是否包含key 'four': " + map.containsKey("four"));
        System.out.println("Map是否包含value 2: " + map.containsValue(2));
        
        System.out.println();
    }
    
    // 5. 字符串操作
    public static void demonstrateStringOperations() {
        System.out.println("5. 字符串操作:");
        String str = "Hello World";
        
        System.out.println("原字符串: " + str);
        System.out.println("长度: " + str.length());
        System.out.println("字符数组: " + Arrays.toString(str.toCharArray()));
        System.out.println("子字符串: " + str.substring(0, 5));
        System.out.println("是否以'He'开头: " + str.startsWith("He"));
        System.out.println("是否以'ld'结尾: " + str.endsWith("ld"));
        System.out.println("替换: " + str.replace("World", "Java"));
        System.out.println("转大写: " + str.toUpperCase());
        System.out.println("转小写: " + str.toLowerCase());
        System.out.println("去掉首尾空格: " + "  Hello  ".trim());
        
        // 分割
        String[] parts = "a,b,c,d".split(",");
        System.out.println("分割结果: " + Arrays.toString(parts));
        
        System.out.println();
    }
    
    // 6. 数学运算
    public static void demonstrateMathOperations() {
        System.out.println("6. 数学运算:");
        
        System.out.println("绝对值: " + Math.abs(-10));
        System.out.println("最大值: " + Math.max(5, 10));
        System.out.println("最小值: " + Math.min(5, 10));
        System.out.println("向上取整: " + Math.ceil(4.3));
        System.out.println("向下取整: " + Math.floor(4.7));
        System.out.println("四舍五入: " + Math.round(4.5));
        System.out.println("平方根: " + Math.sqrt(16));
        System.out.println("幂运算: " + Math.pow(2, 3));
        System.out.println("随机数(0-1): " + Math.random());
        
        System.out.println();
    }
    
    // 7. 输入输出
    public static void demonstrateIOOperations() {
        System.out.println("7. 输入输出:");
        
        // Scanner用于读取输入
        Scanner scanner = new Scanner(System.in);
        System.out.println("Scanner常用方法:");
        System.out.println("- next(): 读取下一个单词");
        System.out.println("- nextLine(): 读取整行");
        System.out.println("- nextInt(): 读取整数");
        System.out.println("- hasNext(): 判断是否还有输入");
        System.out.println("- hasNextInt(): 判断下一个是否为整数");
        
        // BufferedReader (更高效的输入)
        System.out.println("BufferedReader用于高效读取:");
        System.out.println("- readLine(): 读取一行");
        
        System.out.println();
    }
    
    // 8. 排序
    public static void demonstrateSorting() {
        System.out.println("8. 排序:");
        
        // 数组排序
        int[] arr = {5, 2, 8, 1, 9};
        Arrays.sort(arr);
        System.out.println("数组排序: " + Arrays.toString(arr));
        
        // 自定义排序 (降序)
        Integer[] arr2 = {5, 2, 8, 1, 9};
        Arrays.sort(arr2, Collections.reverseOrder());
        System.out.println("降序排序: " + Arrays.toString(arr2));
        
        // List排序
        List<Integer> list = Arrays.asList(5, 2, 8, 1, 9);
        Collections.sort(list);
        System.out.println("List排序: " + list);
        
        // 自定义排序规则
        List<String> words = Arrays.asList("apple", "hi", "banana");
        Collections.sort(words, (a, b) -> a.length() - b.length()); // 按长度排序
        System.out.println("按长度排序: " + words);
        
        System.out.println();
    }
    
    // 9. 查找
    public static void demonstrateSearching() {
        System.out.println("9. 查找:");
        
        int[] sortedArr = {1, 3, 5, 7, 9, 11, 13};
        int target = 7;
        int index = Arrays.binarySearch(sortedArr, target);
        System.out.println("二分查找 " + target + " 的位置: " + index);
        
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
        int pos = Collections.binarySearch(list, 3);
        System.out.println("List中查找3的位置: " + pos);
        
        System.out.println("Collections.max: " + Collections.max(list));
        System.out.println("Collections.min: " + Collections.min(list));
        
        System.out.println();
    }
    
    // 10. 数据结构
    public static void demonstrateDataStructures() {
        System.out.println("10. 数据结构:");
        
        // Stack (用ArrayDeque模拟)
        Deque<Integer> stack = new ArrayDeque<>();
        stack.push(1);
        stack.push(2);
        stack.push(3);
        System.out.println("Stack: " + stack + ", pop: " + stack.pop());
        
        // Queue
        Queue<Integer> queue = new LinkedList<>();
        queue.offer(1);
        queue.offer(2);
        queue.offer(3);
        System.out.println("Queue: " + queue + ", poll: " + queue.poll());
        
        // PriorityQueue (最小堆)
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        pq.offer(3);
        pq.offer(1);
        pq.offer(4);
        pq.offer(2);
        System.out.println("PriorityQueue: " + pq + ", poll: " + pq.poll());
        
        // Deque (双端队列)
        Deque<Integer> deque = new ArrayDeque<>();
        deque.offerFirst(1);
        deque.offerLast(2);
        deque.offerFirst(0);
        System.out.println("Deque: " + deque + ", removeFirst: " + deque.removeFirst() + ", removeLast: " + deque.removeLast());
        
        System.out.println();
    }
}
相关推荐
apcipot_rain2 小时前
天梯赛练习集 时间规划 限时复盘 中档题详解(L1-6~L2-4)
算法
码界筑梦坊2 小时前
353-基于Python的大湾区气候数据可视化分析系统
开发语言·python·信息可视化·数据分析·django·vue·毕业设计
Magic--2 小时前
深入解析管道:最基础的进程间通信(IPC)实现
java·服务器·unix
再卷也是菜2 小时前
第一章、线性代数(2)高斯消元法
线性代数·算法
NAGNIP2 小时前
一文搞懂CNN经典架构-EfficientNet!
算法·面试
如何原谅奋力过但无声2 小时前
【chap11-动态规划(上 - 基础题目&背包问题)】用Python3刷《代码随想录》
数据结构·python·算法·动态规划
架构师沉默2 小时前
为什么国外程序员都写独立博客,而国内都在公众号?
java·后端·架构
带刺的坐椅2 小时前
SolonCode v2026.4.1 发布(比 ClaudeCode 简约的编程智能体)
java·ai·llm·agent·solon-ai·claudecode·soloncode
殷紫川3 小时前
从单体到亿级流量:登录功能全场景设计指南,踩过的坑全给你填平了
java