LeetCode: 151. Reverse Words in a String 翻转字符串中的词

本文介绍了一种将字符串按单词进行反转的方法,并提供了多个示例代码实现。通过对输入字符串中单词的处理,确保反转后的字符串既没有前导也没有尾随空格,并且单词之间的多余空格被压缩为单个空格。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

试题
Given an input string, reverse the string word by word.

Example 1:

Input: “the sky is blue”
Output: “blue is sky the”
Example 2:

Input: " hello world! "
Output: “world! hello”
Explanation: Your reversed string should not contain leading or trailing spaces.
Example 3:

Input: “a good example”
Output: “example good a”
Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.

Note:

A word is defined as a sequence of non-space characters.
Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.
You need to reduce multiple spaces between two words to a single space in the reversed string.
代码:

class Solution {
    public String reverseWords(String s) {
        if(s == null || s.length() == 0) return s;
        
        String[] sArr = s.trim().split(" ");
        StringBuilder temp = new StringBuilder();
        for(int i = sArr.length-1; i >= 0; i--){
            if(sArr[i] == null || sArr[i].equals("")) continue;
            temp.append(sArr[i]);
            temp.append(" ");
        }
        if(temp.length() > 0)
            temp.deleteCharAt(temp.length()-1);
        return temp.toString();
    }
}
class Solution {
    public String reverseWords(String s) {
        StringBuilder out = new StringBuilder();
        if(s==null || s.length()==0) return "";
        
        s = s.trim();
        String tmp = "";
        for(int i=s.length()-1; i>=0; i--){
            char t = s.charAt(i);
            if(t==' '){
                while(i-1>=0 && s.charAt(i-1)==' ') i--;
                out.append(tmp+" ");
                tmp = "";
            }else{
                tmp = t + tmp;
            }
        }
        out.append(tmp);
        
        return out.toString();
    }
}
public String reverseWords(String s) {
        StringBuilder sb = new StringBuilder();
        int i = s.length() - 1;
        while(i >= 0){
            if(s.charAt(i) == ' '){
                i--;
                continue;
            }
            int start = s.lastIndexOf(' ', i);
            sb.append(' ');
            sb.append(s.substring(start + 1, i + 1));
            i = start - 1;
        }
        if(sb.length() > 0){
            sb.deleteCharAt(0);    
        }
        
        return sb.toString();
        
    }

翻转https://www.baidu.com成com.baidu.www://https:

public class Main{
    public static void main(String[] args){
        String in = "https://www.baidu.com";
        Main main = new Main();
        System.out.println(main.split(in));
        System.out.println(main.split2(in));
        System.out.println(main.split3(in));
    }

    private String split(String in){
        if(in==null || in.length()==0) return "";
        StringBuilder ss = new StringBuilder();
        int end = in.length()-1;
        while(end>=0){
            int start = in.lastIndexOf(".",end);
            if(start!=-1){
                ss.append("."+in.substring(start+1,end+1));
            }else{
                start = in.lastIndexOf("://", end);
                if(start!=-1){
                    ss.append("."+in.substring(start+3,end+1));
                }else{
                    ss.append("://"+in.substring(start+1,end+1));
                }
            }
            end = start-1;
        }
        ss.deleteCharAt(0);
        return ss.toString();
    }

    private String split2(String in){
        String[] strs = in.split("\\.");
        StringBuilder out = new StringBuilder();
        for(int i=strs.length-1; i>=0; i--){
            if(i!=0){
                out.append(strs[i]);
                out.append(".");
            }else{
                String[] tmp = strs[i].split("://");
                out.append(tmp[1]);
                out.append("://");
                out.append(tmp[0]);
            }
        }
        return out.toString();
    }
    private String split3(String in){
        String[] strs = in.split("\\.|(://)");
        StringBuilder out = new StringBuilder();
        for(int i=strs.length-1; i>=0; i--){
            if(i!=0){
                out.append(strs[i]);
                out.append(".");
            }else{
                out.deleteCharAt(out.length()-1);
                out.append("://");
                out.append(strs[i]);
            }
        }
        return out.toString();
    }
}
### C语言实现LeetCode 151题(反转字符串中的) 对于给定的任务,在C语言中解决该问题的一种方法是通过手动处理字符串并利用辅助函数来完成特定操作。下面展示了一种可能的解决方案,其中包含了如何定义必要的功能以及它们是如何协同工作的解释。 #### 完整代码示例 ```c #include <stdio.h> #include <string.h> void trim(char *str) { char *end; while (isspace((unsigned char)*str)) str++; end = str + strlen(str) - 1; while(end > str && isspace((unsigned char)*end)) end--; *(end+1) = '\0'; } void reverseString(char* start, char* end){ while(start<end){ char temp=*start; *start++=*end; *end--=temp; } } char* reverseWords(char* s) { int length=strlen(s); if(length==0)return ""; // Trim leading and trailing spaces trim(s); char *result=(char*)malloc(strlen(s)+2); // Extra space for potential extra space at the end and null terminator result[0]='\0'; char word[50]; // Assuming no single word will exceed this limit int index=0; for(int i=0;i<=length;i++){ if(i==length || s[i]==' '){ if(index>0){ reverseString(word,word+index-1); strcat(result,word); if(i!=length)strcat(result," "); memset(word,'\0',sizeof(word)); index=0; } }else{ word[index++]=s[i]; } } return result; } ``` 此程序首先移除了输入字符串两端多余的空白字符[^1]。接着遍历整个字符串,每当遇到空格或到达字符串结尾时,就调用`reverseString()`函数翻转当前收集到的一个完整的,并将其追加到最终的结果串后面。为了防止最后多出不必要的空格,在每次添加新之前会检查当前位置是否为原字符串的实际末端位置[^2]。 注意这里假设单个语长度不会超过预设的最大值(这里是49),如果存在更长的情况,则需要调整数组大小或者采用动态分配的方式存储临时变量`word`。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值