zoukankan      html  css  js  c++  java
  • 算法 (1) 数组和字符串一些常用方法

    一、数组

    颠倒数组元素的顺序:

    package algorithm;
    
    /**
     * 颠倒数组元素的顺序
     */
    public class ReverseArray {
    
        public static void main(String[] args) {
            int array[] = {4, 3, 1, 9, 8};
            reverseArray(array);
            for(int a : array){
                System.out.print(a + " ");
            }
        }
    
        public static void reverseArray(int a[]){
            int N = a.length;
            for(int i=0; i<N/2; i++){
                int temp = a[i];
                a[i] = a[N-1-i];
                a[N-1-i] = temp;
            }
        }
    }

    二、典型的字符串处理代码

    package algorithm;
    
    /**
     * 〈典型的字符串处理代码〉<br>
     */
    public class StringTest {
        public static void main(String[] args) {
            System.out.println(isPalindrome("alola"));      //true
            String s = "hello";
            System.out.println(isSorted(s.split("")));  //false  split("")之后第一个数组元素是空
        }
    
        /**
         * 判断字符串是否是一条回文
         * @param s
         * @return
         */
        public static boolean isPalindrome(String s){
            int N = s.length();
            for(int i=0; i<N/2; i++) {
                if (s.charAt(i) != s.charAt(N - 1 - i)) {
                    return false;
                }
            }
            return true;
        }
    
        /**
         * 检查一个字符串数组中的元素是否已按照字母表顺序排列
         * @param a
         * @return
         */
        public static boolean isSorted(String[] a){
            for(int i=1; i<a.length; i++){
                if(a[i-1].compareTo(a[i]) > 0){
                    return false;
                }
            }
            return true;
        }
    }
  • 相关阅读:
    不要同时使用ReentrantLock类与synchronized关键字锁定会修改同一个资源的不同方法
    java中volatile关键字的含义
    浅谈操作系统对内存的管理
    Java线程池使用说明
    写在清明节之后
    PY一天一学
    24小时只睡了1个小时
    关于团队关于吐槽
    出尔反尔
    时间都去哪儿了?
  • 原文地址:https://www.cnblogs.com/tenWood/p/10026472.html
Copyright © 2011-2022 走看看