首页 > 技术文章 > 字符串中单词去多余空格

tecnologycc 2018-12-18 18:31 原文

思路利用快慢指针。时间复杂度0(n)

public static void main(String[] args) throws InterruptedException {
        String str = "abc   cdadf   fde  fdgg   gfgax   a ";
        char[] charArray = str.toCharArray();
        int slowIndex = 0;
        int fastIndex = 0;
        while (fastIndex < charArray.length) {
            if (charArray[fastIndex] == ' ') {
                fastIndex++;
            } else {
                if (slowIndex != fastIndex) {
                    char temp = charArray[slowIndex];
                    charArray[slowIndex] = charArray[fastIndex];
                    charArray[fastIndex] = temp;
                    slowIndex++;
                    fastIndex++;
                    continue;
                }
                fastIndex++;
                slowIndex = fastIndex;
            }
        }
        System.out.println(new String(charArray));
    }

推荐阅读