编程题:倒置字符串
https://www.nowcoder.com/practice/ee5de2e7c45a46a090c1ced2fdc62355?tpId=85&&tqId=29867&rp
=1&ru=/activity/oj&qru=/ta/2017test/question-ranking
【题目解析】:
本题题意很简单,就是将一段字符串中的前后单词交换,以单词为单位逆置。
【解题思路 1 】:
先将整个字符串逆置过来,再遍历字符串,找出每个单词,对单词逆置
import java.util.*;
public class Main{
public static void reverse(char[] array,int start,int end) {
while(start < end) {
char tmp = array[start];
array[start] = array[end];
array[end] = tmp;
start++;
end--;
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
char[] ch = s.toCharArray();
int len = ch.length;
//1、整体进行了逆置
reverse(ch,0,len-1);
int i = 0;//遍历ch数组
while( i < len ) {
int j = i;
while(j < len && ch[j] != ' ') {
j++;
}
if(j < len) {
reverse(ch,i,j-1);
i = j+1;
}else{
reverse(ch,i,j-1);
i = j;
}
}
String str = new String(ch);
System.out.println(str);
}
}
 posted on 2023-10-23 13:08  dapaige  阅读(11)  评论(0)    收藏  举报  来源