您的位置:首页 > 编程语言 > Go语言

Given an array of characters which form a sentence of words, give an efficient algorithm to reverse

2012-08-23 11:12 288 查看
Given an array of characters which form a sentence of words, give an efficient algorithm to reverse the order of the words (not characters) in it.























import java.util.ArrayList;

import java.util.List;

public class Reverse {

public static void main(String args[]) {

String sentence = "one world one dream";

List<String> words = new ArrayList<String>();

int j = 0;

for (int i = 0; i < sentence.length(); i++) {

if (sentence.charAt(i) == ' ') {

words.add(sentence.substring(j,i ));

j=i+1;

}

}

words.add(sentence.substring(j));





for(int i=0;i<words.size()/2;i++)

{

String temp=words.get(i);

words.set(i,words.get(words.size()-i-1));

words.set(words.size()-i-1,temp);

}



for(int i=0;i<words.size();i++)

System.out.print(words.get(i)+" ");



}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐