String 常用方法最优算法实现总结 (二)

1. String getOrderedString(boolean isDuplicated, String … str)

说明:

Orders all characters in the input strings and return the ordered string.(note: only considering the alphabets and digits)

i.e:

(false, {"ahcdx", "abcuy", "cejm"}) ->"abcdehjmuxy"

(true, {"ahcdx", "abcuy", "cejm"}) ->"aabcdehjmuxy"

/**
     * Orders all characters in the input strings without duplicated str.
     *
     * @Title: getOrderedString
     * @param isDuplicated true/false
     * @param str input str
     * @return ordered string
     */
    public static String getOrderedString(boolean isDuplicated, String... str) {
        if (str == null || str.length == 0) {
            return null;
        }

        // initialize array
        int[] charArrayTmp = new int[MAX_CHAR_LENGTH];
        System.arraycopy(CHARARRAY, 0, charArrayTmp, 0, MAX_CHAR_LENGTH);

        int length = str.length;
        String value = null;
        int valueLength = 0;
        char tempValue;
        int totalCounts = 0;

        // merge and sort the input strs
        for (int i = 0; i < length; i++) {
            value = str[i];
            valueLength = value.length();
            totalCounts += valueLength;

            for (int j = 0; j < valueLength; j++) {
                tempValue = value.charAt(j);

                if (isDuplicated) {
                    charArrayTmp[tempValue] += 1;
                } else {
                    charArrayTmp[tempValue] = 1;
                }

            }
        }

        char[] newChar = new char[totalCounts];
        int counts = 0;
        int len = 0;
        // append result that has been merged and sorted
        for (int i = MIN_CHAR_LENGTH; i < MAX_CHAR_LENGTH; i++) {
            len = charArrayTmp[i];

            if (len != 0) {
                for (int j = 0; j < len; j++) {
                    newChar[counts++] = (char) i;
                }
            }

        }
        return new String(newChar, 0, counts);
    }

2.  List<String> getMostLongDifferent(String str)

说明:

Returns the longest consecutive different substring.

i.e:

("abcabefg") -> "cabefg"

    /**
     * @Description: get the longest consecutive different substring.
     * @Title: getMostLongDifferent
     * @param str input string
     * @return the longest consecutive different substring of input
     */
    public static List<String> getMostLongDifferent(String str) {
        if (isEmpty(str)) {
            return null;
        }
        int len = str.length();
        Map<Character, Integer> cursor = new HashMap<Character, Integer>();
        cursor.put(str.charAt(0), 0);
        int[] lengthAt = new int[len];
        lengthAt[0] = 1;
        int max = 0;
        for (int i = 1; i < len; i++) {
            char cha = str.charAt(i);

            if (cursor.containsKey(cha)) {
                lengthAt[i] = Math.min(lengthAt[i - 1] + 1, i - cursor.get(cha));
            } else {
                lengthAt[i] = lengthAt[i - 1] + 1;
            }
            max = (max >= lengthAt[i]) ? max : lengthAt[i];
            cursor.put(cha, i);
        }

        List<String> resultList = new ArrayList<String>();
        for (int i = 0; i < len; i++) {
            if (max == lengthAt[i]) {
                String resultString = str.substring(i - max + 1, i + 1);
                if (!resultList.contains(resultString)) {
                    resultList.add(resultString);
                }
            }
        }
        return resultList;
    }

3. String normalizeSpace(String str)

说明:

Remove leading and trailing whitespace and then replacing sequences of whitespace characters by a single space.

/**
     * Remove leading and trailing whitespace and then replacing sequences of whitespace characters.
     * by a single space
     *
     * @param str the string need to be normalize space
     * @return string result after normalize space
     */
    public static String normalizeSpace(String str) {
        if (str == null) {
            return null;
        }

        str = str.trim();

        if (str.length() <= 3) {
			return str;
		}

        if (str.indexOf(CommonConstants.DOUBLE_BLANKS, 1) >= 0) {
        	char[] chars = str.toCharArray();
            int index = 0;

	        for (int i = 0, len = chars.length; i < len; i++) {
	            if (chars[i] != CommonConstants.CHAR_BLANKS || chars[i - 1] != CommonConstants.CHAR_BLANKS) {
	                chars[index++] = chars[i];
	            }
	        }

	        return new String(chars, 0, index);
        } else {
			return str;
		}
    }

时间: 2024-08-29 03:51:18

String 常用方法最优算法实现总结 (二)的相关文章

String 常用方法最优算法实现总结 (三) -- findCommonSubstring 和difference

1. String difference(final String str1, final String str2) 说明:Compares two Strings, and returns the portion where they differ. i.e: ("ahc", "bcu") -> "ahbu" /** * * @Title: difference * @Description: Compares two Strings,

JVM内存分配及String常用方法

一,JVM内存分配和常量池 ? 在介绍String类之前,先来简单分析一下在JVM中,对内存的使用是如何进行分配的.如下图所示(注意:在jdk1.8之后便没有方法区了): ? ? 如上JVM将内存分为多个不同的区域,这些区域都有各自的用途.创建和销毁的时间,有些区域随虚拟机进程的启动而存在,有些区域则是依赖用户线程的启动和结束来建立和销毁. ? 区域名称的说明: 1.1,方法区: ? 属于数据共享内存区域,存储已被虚拟机加载的类信息.常量.静态变量.即时编译器编译后的代码等数据. 1.2,虚拟机

String常用方法

String常用方法 String s1="abc" s1是一个类类型的变量,"abc"是一个对象 字符串一旦初始化就不可以被改变 String s2=new String("abc") s1在内存中是一个对象,s2在内存中是两个对象 String覆写了Object的equals方法,比较的是两个字符串是否相等. 将此 String 与另一个 String 比较,不考虑大小写:boolean equalsIgnoreCase(str) 字符串常见

Javascript语言精粹之String常用方法分析

Javascript语言精粹之String常用方法分析 1. String常用方法分析 1.1 String.prototype.slice() slice(start,end)方法复制string的一部分来构造一个新的字符串 start<0时,它将于string.length相加 end参数可选,默认值为string.length.如果end<0,它将于string.length相加 var text='and in it he say " Any damn fool could'

java之string常用方法&lt;二&gt;

1. 获取方法 int length()  获取字符串的长度, char charAt(int index) 获取特定位置的字符 (角标越界), int indexOf(String str) 获取特定字符的位置(overload),查找子串第一次出现的索引值,若没找到则返回-1表示, int lastIndexOf(int ch) 获取最后一个字符的位置,查找子串最后一次出现的索引值,若没找到则返回-1表示. public class Demo02 { public static void m

JavaScript String常用方法和属性

一.string中的常用属性 1. length 说明: 字符串的长度属性,一直保持跟踪着该字符串中包含的字符数. 二.string中的常用方法 1. toLowerCase() 和 toUpperCase() 说明: toLowerCase(): returns a copy of the string with its letters converted to lowercase. Numbers, symbols, and other characters are not affected

js中String常用方法详解及String对象方法扩展

一.JavaScript 中 slice .substr 和 substring的区别: 1: String.slice(start,end): 一个新的字符串.包括字符串 stringObject 从 start 开始(包括 start)到 end 结束(不包括 end)为止的所有字符. 2: String.substring(start,end) 这个就有点特别了,它是先从start,end里找出一个较小的值. 然后从字符串的开始位置算起,截取较小值位置和较大值位置之间的 字符串,截取出来的

Java 中String常用方法

java中String的常用方法 1.length() 字符串的长度 例:char chars[]={'a','b'.'c'}; String s=new String(chars); int len=s.length(); 2.charAt() 截取一个字符 例:char ch; ch="abc".charAt(1); 返回'b' 3. getChars() 截取多个字符 void getChars(int sourceStart,int sourceEnd,char target[

Java中String常用方法

java中String的常用方法1.length() 字符串的长度 例:char chars[]={'a','b'.'c'}; String s=new String(chars); int len=s.length(); 2.charAt() 截取一个字符 例:char ch; ch="abc".charAt(1); 返回'b' 3. getChars() 截取多个字符 void getChars(int sourceStart,int sourceEnd,char target[]