标签:
1.给定一个字符串,按单词将该字符串逆序,比如给定"This is a sentence",则输出是"sentence a is This",为了简化问题,字符串中不包含标点符号。
分两步
1 先按单词逆序得到"sihT si a ecnetnes"
2 再整个句子逆序得到"sentence a is This"
public class test { public static void main(String[] args) { // Scanner in = new Scanner(System.in); // String str = new String(); // while(in.hasNext()){ // // str= in.nextLine(); String str = "hello world girl abcd"; char[] chs = str.toCharArray(); reverseWords(chs, 0, str.length()-1); int left = 0,right; for(int i = 0; i<str.length();i++){ if(chs[i] == ‘ ‘){ right = i-1; reverseWords(chs, left , right); left = i+1; }else{ right = i; } if(right == str.length()-1){ reverseWords(chs, left , right); } } for(char s:chs){ System.out.print(s); } // } } public static void reverseWords(char[] str, int i, int j){ while(i<j){ char temp = str[i]; str[i] = str[j]; str[j] = temp; i++; j--; } }
标签:
原文地址:http://my.oschina.net/elain/blog/504331