LeetCode 151.Reverse Words in a String【Java】

Title description

Reverse the words in the string

AC code

The idea is: first reverse each word, and then reverse the entire string.
1. Why in the reverse function ch=reverse(ch,i,j-1);, we use j to indicate where the space is, so the value corresponding to the subscript j is a space, and the end we exchange should be the characters before the first space, so j-1 is required.
2. Why do I need to remove the extra parts when performing the overall reversal? Because some strings may have extra spaces, after reversal, there are no extra spaces, there are no spaces at the beginning and end of the string, and there is only one space between words at most, so there will be empty positions after reversal. Then there will be other words in these positions. Our results do not need these extra characters, so we need to intercept them.

/*
                    the sky is blue
先反转每个单词:      eht yks si eulb
然后反转整个字符串:   blue is sky the
*/
class Solution {
    public String reverseWords(String s) {
        int k=0;
        char[] ch=s.toCharArray();
        for(int i=0;i<ch.length;i++){
        	//寻找第一个单词的第一个位置,第一个字符可能是空格
            while(i<ch.length&&ch[i]==' ')i++;
            if(i==ch.length)break;
            int j=i;
            //通过空格分隔单词
            while(j<ch.length&&ch[j]!=' ')j++;
            //反转单词
            ch=reverse(ch,i,j-1);
            //添加空格分割单词和单词
            if(k!=0) ch[k++]=' ';
            //修改字符数组
            while(i<j){
                ch[k++]=ch[i++];
            } 
        }
        //去掉多余部分后的字符串进行整体反转
        StringBuilder sb=new StringBuilder(new String(ch).substring(0,k)).reverse();
		return sb.toString();
    }
	
	//字符串反转
    public char[] reverse(char[] array,int i,int j){
        while(i<j){
            char c=array[i];
            array[i]=array[j];
            array[j]=c;
            i++;j--;
        }
        return array;
    }
}

There are other methods, you can make full use of String class methods, double pointers to solve.

Published 201 original articles · Like9 · Visitors 10,000+

Guess you like

Origin blog.csdn.net/weixin_40992982/article/details/105498784