题目:翻转字符串

来源:互联网 发布:大数据工程师压力大吗 编辑:程序博客网 时间:2024/05/20 18:54

给定一个字符串,逐个翻转字符串中的每个单词。

您在真实的面试中是否遇到过这个题?
Yes
哪家公司问你的这个题?AirbnbAlibaba Amazon Apple Baidu Bloomberg Cisco Dropbox Ebay Facebook Google Hulu Intel Linkedin Microsoft NetEase Nvidia Oracle Pinterest Snapchat Tencent Twitter Uber Xiaomi Yahoo Yelp Zenefits
感谢您的反馈
样例

给出s = "the sky is blue",返回"blue is sky the"

说明

  • 单词的构成:无空格字母构成一个单词
  • 输入字符串是否包括前导或者尾随空格?可以包括,但是反转后的字符不能包括
  • 如何处理两个单词间的多个空格?在反转字符串中间空格减少到只含一个

标签 Expand
字符串处理



相关题目 Expand         



思想:先将整个字符串以空格划分保存在arr,再遍历arr将非空格的word逆序放到arrword数组中,再遍历arrword。

public class Solution {
    /**
     * @param s : A string
     * @return : A string
     */
    public String reverseWords(String s) {
        // write your code
          if (null == s || 0 == s.length())
               return s;
          String[] arrs = s.split(" ");
          StringBuffer result = new StringBuffer();
          String[] arrWord = new String[arrs.length];
          int k = arrWord.length - 1;
          for (int i = 0; i < arrs.length; i++) {
               if (arrs[i] != " ") {
                    arrWord[k--] = arrs[i];
               }
          }
          for (int i = 0; i < arrWord.length; i++) {
               if (i == arrWord.length - 1) {
                    result.append(arrWord[i]);
               } else if (arrWord[i] != null || arrWord[i].length() != 0) {
                    result.append(arrWord[i] + " ");
               }
          }
          return result.toString();
    }
}






0 0