【字符串专题】—— 翻转字符串与其子串

LeetCode 151: 颠倒字符串中的单词

【字符串专题】—— 翻转字符串与其子串_第1张图片
⭕️ 解题思路: (水一篇博客)

去除字符串中多余的空格:字符串前面、字符串后面,字符串中单词之间只保留一个空格

class Solution {
    public String reverseWords(String s) {
        //去除重复空格
        StringBuffer sb = deleteSpace(s);
        //翻转整个字符符串
        reverseString(sb, 0, sb.length() - 1);
        //翻转单词
        reverseEachWord(sb);
        return sb.toString();
    }
    public static StringBuffer deleteSpace(String s){
        int left = 0;
        int right = s.length() - 1;
        while(left <= right && s.charAt(left) == ' '){
            left++;
        }
        while(left <= right && s.charAt(right) == ' '){
            right--;
        }
        StringBuffer sb = new StringBuffer();
        while(left < right){
            char ch = s.charAt(left);
            if(ch != ' ' || sb.charAt(sb.length() - 1) != ' '){
                sb.append(ch);
            }
            left++;
        }
        return sb;
    }
    public static void reverseString(StringBuffer sb, int start, int end){
        while(start < end){
            char ch = sb.charAt(start);
            sb.setCharAt(start, sb.charAt(end));
            sb.setCharAt(end, ch);
        }
    }

    public static void reverseEachWord(StringBuffer sb){
        //设置两个指针
        int start = 0;
        int end = 1;
        int n = sb.length();
        while(start < n){
            char ch = sb.charAt(start);
            while(ch != ' '){
                end++;
            }
            //将每个单词进行翻转[此时end指向的字符为空格]
            reverseString(sb, start, end - 1);
            start = end + 1;
            end = start + 1;
        }
    }
}


你可能感兴趣的:(算法,数据结构,java,leetcode,算法)