[LeetCode] 151 Reverse Words in a String 翻转字符串中的单词
详解 "\\s+"
正则表达式中\s匹配任何空白字符,包括空格、制表符、换页符等等, 等价于[ \f\n\r\t\v]
- \f -> 匹配一个换页
- \n -> 匹配一个换行符
- \r -> 匹配一个回车符
- \t -> 匹配一个制表符
- \v -> 匹配一个垂直制表符
而“\s+”则表示匹配任意多个上面的字符。另因为反斜杠在Java里是转义字符,所以在Java里,我们要这么用“\\s+”.
public String reverseWords(String s) { String[] tem = s.trim().split("\\s+"); String res = ""; for (int i = tem.length - 1; i > 0; i--) { res += tem[i] + " "; } res = res + tem[0]; return res; }
//原始方法 BY jeantimex //先逆转整个字符串,然后对逆转的字符串逆转每个词,最后去掉该去的空格 public String reverseWords(String s) { if (s == null) return null; char[] a = s.toCharArray(); int n = a.length; // step 1. reverse the whole string reverse(a, 0, n - 1); // step 2. reverse each word reverseWords(a, n); // step 3. clean up spaces return cleanSpaces(a, n); } void reverseWords(char[] a, int n) { int i = 0, j = 0; while (i < n) { while (i < j || i < n && a[i] == ' ') i++; // skip spaces while (j < i || j < n && a[j] != ' ') j++; // skip non spaces reverse(a, i, j - 1); // reverse the word } } // trim leading, trailing and multiple spaces String cleanSpaces(char[] a, int n) { int i = 0, j = 0; while (j < n) { while (j < n && a[j] == ' ') j++; // skip spaces while (j < n && a[j] != ' ') a[i++] = a[j++]; // keep non spaces while (j < n && a[j] == ' ') j++; // skip spaces if (j < n) a[i++] = ' '; // keep only one space } return new String(a).substring(0, i); } // reverse a[] from a[i] to a[j] private void reverse(char[] a, int i, int j) { while (i < j) { char t = a[i]; a[i++] = a[j]; a[j--] = t; } }
[LeetCode] 186. Reverse Words in a String II 翻转字符串中的单词之二
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.
Subscribe to see which companies asked this question.
public static void reverse(char[] s, int start, int end){ while(start<end){ char tmp = s[end]; s[end]=s[start]; s[start]=tmp; start++; end--; } } /* 557. Reverse Words in a String III */ public static String reverseWords(String s) { char[] a = s.toCharArray(); int start=0; for(int i=0;i<s.length();i++){ if (a[i]==' '){ int end=i-1; reverse(a,start,end); start=i+1; } } reverse(a, start,s.length() - 1); return new String(a); } }