一、题目链接
http://noi.openjudge.cn/ch0107/23/
二、解题思路(Java)
三、解题思路(C++)
四、Java程序
import java.util.Scanner;
public class Main {
public String removeRedundantSpaces(String text) {
StringBuilder ans = new StringBuilder();
String[] words = text.split(" ");
ans.append(words[0]);
for (int i = 1; i < words.length; i++) {
if (!words[i].isEmpty()) {
ans.append(" " + words[i]);
}
}
return ans.toString();
}
public static void main(String[] args) {
Main test = new Main();
Scanner input = new Scanner(System.in);
String text = input.nextLine();
System.out.print(test.removeRedundantSpaces(text));
}
}
五、C++程序
#include <iostream>
using namespace std;
int main()
{
string text;
getline(cin, text);
int n = text.length();
char chars[n];
chars[0] = text[0];
int m = 1;
int i;
for (i = 1; i < n; i++)
{
if (text[i] != ' ' ||
text[i] == ' ' && text[i - 1] != ' ')
{
chars[m] = text[i];
m++;
}
}
for (i = 0; i < m; i++)
{
cout << chars[i];
}
return 0;
}