[原]《面试题精选》08.颠倒句子中单词的顺序
题目:输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。句子中单词以空格符隔开。为简单起见,标点符号和普通字母一样处理。
例如输入“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
charvalue at the specified index. An index ranges from0tolength() - 1. The firstcharvalue of the sequence is at index0, the next at index1, and so on, as for array indexing.If the
charvalue specified by the index is a surrogate, the surrogate value is returned. -
- Specified by:
charAtin interfaceCharSequence
-
- Parameters:
index- the index of thecharvalue.- Returns:
- the
charvalue at the specified index of this string. The firstcharvalue is at index0. - Throws:
IndexOutOfBoundsException- if theindexargument 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
beginIndexand 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 thebeginIndexis negative, orendIndexis larger than the length of thisStringobject, orbeginIndexis larger thanendIndex.
作者:SpeedMe 发表于2014-4-4 9:54:54 原文链接
阅读:236 评论:0 查看评论
浙公网安备 33010602011771号