LeetCode(Sorting)1859. Sorting the Sentence
1.问题
A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of lowercase and uppercase English letters.
A sentence can be shuffled by appending the 1-indexed word position to each word then rearranging the words in the sentence.
For example, the sentence “This is a sentence” can be shuffled as “sentence4 a3 is2 This1” or “is2 sentence4 This1 a3”.
Given a shuffled sentence s containing no more than 9 words, reconstruct and return the original sentence.
Example 1:
Input: s = “is2 sentence4 This1 a3”
Output: “This is a sentence”
Explanation: Sort the words in s to their original positions “This1 is2 a3 sentence4”, then remove the numbers.
Example 2:
Input: s = “Myself2 Me1 I4 and3”
Output: “Me Myself and I”
Explanation: Sort the words in s to their original positions “Me1 Myself2 and3 I4”, then remove the numbers.
Constraints:
- 2 <= s.length <= 200
- s consists of lowercase and uppercase English letters, spaces, and digits from 1 to 9.
- The number of words in s is between 1 and 9.
- The words in s are separated by a single space.
- s contains no leading or trailing spaces.
2. 解题思路
方法1:
1.s去掉空白,转成数组s1;新建数组str,长度为s1;定义一个空的String为result
2.遍历数组s1,将元素中的最后索引的数值,放入到str数组中,取从0到数值之前的字符
3.数组的元素遍历,并添加到result
4.返回result
3. 代码
代码1:
class Solution {
public String sortSentence(String s) {
String[] s1 = s.split(" ");//1.s去掉空白,转成数组s1;新建数组str,长度为s1;
String[] str=new String[s1.length];
for(int i=0;i<s1.length;i++){
//2.遍历数组s1,将元素中的最后索引的数值,放入到str数组中,取从0到数值之前的字符
int index= s1[i].length()-1;
int nums= Character.getNumericValue( s1[i].charAt(index));
// int index = Integer.parseInt (String.valueOf ( s1[i].charAt (index));
//或者不需要转成int,char也是可以
//char nums= s1[i].charAt(index);str[nums-'1']= s1[i].substring(0,index)
str[nums-1]= s1[i].substring(0,index);
}
return String.join(" ", str);//4.使用join()插入空白,返回str
}
}
解题思路基本相同,不同的在于for循环遍历放入到String result中,把最后的的空格用trim()方法去除
class Solution {
public String sortSentence(String s) {
String[] s1 = s.split(" ");//1.s去掉空白,转成数组s1;新建数组str,长度为s1,定义String的result为空;
String[] str=new String[s1.length];
String result = "";
for(int i=0;i<s1.length;i++){
//2.遍历数组s1,将元素中的最后索引的数值,放入到str数组中,取从0到数值之前的字符
int index= s1[i].length()-1;
int nums= Character.getNumericValue( s1[i].charAt(index));
// int index = Integer.parseInt (String.valueOf ( s1[i].charAt (index));
//或者不需要转成int,char也是可以
//char nums= s1[i].charAt(index);str[nums-'1']= s1[i].substring(0,index)
str[nums-1]= s1[i].substring(0,index);
}
for (int i = 0; i < str.length; i++) {
result += str[i] + " ";
}
return result.trim();//4.返回result
}
}
代码2:
和代码1解题思路基本相同
class Solution {
public String sortSentence(String s) {
String []ans = new String[s.split(" ").length];
for(String st: s.split(" ")){
ans[st.charAt(st.length()-1) - '1'] = st.substring(0,st.length()-1);
}
return String.join(" ", ans);
}
}
还没有评论,来说两句吧...