Reverse String Question
来源:互联网 发布:华为批量配置端口 编辑:程序博客网 时间:2024/06/06 03:41
Reverse String Question
1 Reverse the string word by word (from leetcode)
For example,
Given s = "the sky is blue",
return "blue is sky the".
Clarification:
What constitutes a word? A sequence of non-space characters constitutes a word.
Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces.
How about multiple spaces between two words?
Reduce them to a single space in the reversed string.
Solution 1: with extra space
use split function to split words in the string and store in an array, then append word[i] + ” “ to new string
at last return s.substring(0, s.length() -1)
这个方法面试时被问过如果不用substring, 如果做,当时想的是判断是不是最后一个就好,但是其实不对,testcase ”_1“ (这里用_表示空格)
word[] = {"" , "1"}, 所以返回还是"1_" Wrong answer!可以用deleteCharAt函数代替
if(reverse.charAt(reverse.length()-1) == ' ')reverse.deleteCharAt(reverse.length()-1);
reverse twice
first reverse: "uelb si yks eht"
second reverse each word" blue is sky the"
reverse use two pointer
code see leetcode solution
2 from yahoo interview question
和leetcode的题目不一样, 是reverse每个单词,比如 “who are you” ---> "ohw era uoy",
要求 in place,有个特殊情况是如果每个单词前后有很多空格,要保留这些空格
//two pointerpublic static void reverse(char[] s){if(s == null || s.length <= 1){return;}//two pointerfor(int i = 0, j =0; j <= s.length; j++){if(j == s.length ||s[j] == ' '){//reverse s[i] to s[j- 1]reverseWord(s, i, j- 1);while(j < s.length && s[j] == ' '){j++; // skip space}i = j;}}}private static void reverseWord(char[] s, int start, int end){//end = end-1;while(start < end){char tmp = s[start];s[start] = s[end];s[end] = tmp;start++;end--;}}
- Reverse String Question
- Reverse string
- String Reverse
- reverse string
- string reverse
- reverse string
- reverse string
- Reverse String
- reverse string
- Reverse String
- Reverse String
- Reverse String
- Reverse String
- Reverse String
- Reverse String
- Reverse String
- Reverse String
- reverse string
- Leetcode Largest Number
- 书法教育在高校素质教育中的地位及其实施
- JSP自定义标签开发入门
- ubifs - superblock
- easyui datagrid实现复选框的多选和单选删除
- Reverse String Question
- Android - Bug:The content of the adapter has changed but ListView did not receive a notification.
- 困扰我很久的 字符串常量指针问题
- 【BZOJ】【P3210】【花神的浇花集会】【题解】【曼哈顿距离变形】
- JS中用于精确计算的加减乘除方法
- flex通过AdvancedDataGrid合并单元格,导出为excel表格
- hdoj 2036 改革春风吹满地
- 七段数码管显示
- Apache Maven入门实例以及了解maven的核心概念