zoukankan      html  css  js  c++  java
  • 【LeetCode】557. Reverse Words in a String III

    Difficulty: Easy

     More:【目录】LeetCode Java实现

    Description

    Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

    Example 1:

    Input: "Let's take LeetCode contest"
    Output: "s'teL ekat edoCteeL tsetnoc"
    

    Note: In the string, each word is separated by single space and there will not be any extra space in the string.

    Intuition

    Find the start and end of each word, then reverse each word.

    Solution

        public String reverseWords(String s) {
            if(s==null || s.length()==0)
                return s;
            StringBuilder sb = new StringBuilder(s);
            int start=0;
            int end=0;
            while(start<s.length()){
                while(end<s.length() && s.charAt(end)!=' ')
                    end++;
                reverse(sb,start,end-1);
                end++;
                start=end;
            }
            return sb.toString();
        }
        
        private void reverse(StringBuilder sb,int start,int end){
            while(start<end){
                char temp=sb.charAt(start);
                sb.setCharAt(start,sb.charAt(end));
                sb.setCharAt(end,temp);
                start++;
                end--;
            }
        }
    

      

    Complexity

    Time complexity : O(n)

    Space complexity :  O(1)

    What I've learned

    1. Learn how to get the start and end of each word.

     More:【目录】LeetCode Java实现

  • 相关阅读:
    epoll 实现回射服务器
    select函数的介绍和使用
    期末项目需求分析报告
    Spring AOP Capabilities and Goals
    Domain Logic approaches
    Lamda Expression
    CDI furture
    23种设计模式
    connector for python
    Spring reference
  • 原文地址:https://www.cnblogs.com/yongh/p/10032533.html
Copyright © 2011-2022 走看看