《面试题甄选》08.颠倒句子中单词的顺序
《面试题精选》08.颠倒句子中单词的顺序
总结:其实这道题没太大难度,关键是考察String类函数的熟悉程度,用到的函数有:
题目:输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。句子中单词以空格符隔开。为简单起见,标点符号和普通字母一样处理。
例如输入“I am a student.”,则输出“student. a am I”。
分析:此题思路应该很清晰,算法上没什么,但是对String字符串的处理时面试中常见问题。遇到颠倒顺序的我们很容易就想到使用数据结构栈,首先我们利用空格来分割单词,然后将单词存入栈中,然后出栈。
import java.util.* ; public class SubString{ public static void reversalString(String str){ Stack<String> s = new Stack<String>() ; int temp = 0 ; int i=0 ; for(;i<str.length();i++){ if(str.charAt(i)==' '){ s.push(str.substring(temp,i)) ; temp = i + 1; } } s.push(str.substring(temp,i)) ; while(!s.empty()){ System.out.print(s.pop()+" ") ; } } public static void main(String args[]){ reversalString("I am a student.") ; //print:student. a am I } }
总结:其实这道题没太大难度,关键是考察String类函数的熟悉程度,用到的函数有:
1. charAt
public char charAt(int index)
-
Returns the
char
value at the specified index. An index ranges from0
tolength() - 1
. The firstchar
value of the sequence is at index0
, the next at index1
, and so on, as for array indexing.If the
char
value specified by the index is a surrogate, the surrogate value is returned. -
- Specified by:
charAt
in interfaceCharSequence
-
- Parameters:
index
- the index of thechar
value.- Returns:
- the
char
value at the specified index of this string. The firstchar
value is at index0
. - Throws:
IndexOutOfBoundsException
- if theindex
argument is negative or not less than the length of this string.
2. substring
public String substring(int beginIndex,
int endIndex)
-
Returns a new string that is a substring of this string. The substring begins at the specified
beginIndex
and extends to the character at indexendIndex - 1
. Thus the length of the substring isendIndex-beginIndex
.Examples:
"hamburger".substring(4, 8) returns "urge" "smiles".substring(1, 5) returns "mile"
-
- Parameters:
beginIndex
- the beginning index, inclusive.endIndex
- the ending index, exclusive.- Returns:
- the specified substring.
- Throws:
IndexOutOfBoundsException
- if thebeginIndex
is negative, orendIndex
is larger than the length of thisString
object, orbeginIndex
is larger thanendIndex
.