zoukankan      html  css  js  c++  java
  • [原]《面试题精选》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 char value at the specified index. An index ranges from 0 to length() - 1. The first char value of the sequence is at index 0, the next at index 1, 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 interface CharSequence
    Parameters:
    index - the index of the char value.
    Returns:
    the char value at the specified index of this string. The first char value is at index 0.
    Throws:
    IndexOutOfBoundsException - if the index 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 index endIndex - 1. Thus the length of the substring is endIndex-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 the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.

    作者:SpeedMe 发表于2014-4-4 9:54:54 原文链接
    阅读:236 评论:0 查看评论
  • 相关阅读:
    UITextView自适应高度解决方法
    UITextView自适应高度出现的问题
    UITextView出现的一些问题
    服务器终于好了!
    Update语句
    VS.NET经验与技巧
    唯一约束
    由C#风潮想起的-给初学编程者的忠告
    location.search在客户端获取Url参数的方法
    Web Services 入门概念
  • 原文地址:https://www.cnblogs.com/huanglei/p/3677702.html
Copyright © 2011-2022 走看看