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.
解题思路:把句子拆分成一个个的字母,以单词中间字母为中心,前后对称位置的字母交换位置
public class Solution {
public String reverseWords(String s) {
String[] strs = s.split(" ");
String result = "";
int len = strs.length;
for (int i = 0; i < len - 1; i++)
result += reverse(strs[i]) + " ";
result += reverse(strs[len - 1]);
return result;
}
public String reverse(String str) {
String result = "";
int len = str.length();
for (int i = 0; i < len; i++)
result = str.charAt(i) + result;
return result;
}
}
本文介绍了一种算法,该算法可以在保持空格和单词原有顺序的同时,反转字符串中每个单词内的字符顺序。通过实例演示了如何实现这一功能,并提供了一个Java代码示例。
479

被折叠的 条评论
为什么被折叠?



