算法 (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;
    }
}
原文地址:https://www.cnblogs.com/tenWood/p/10026472.html