文章

454

粉丝

0

获赞

1

访问

10.4k

头像
判断数字位置 题解(四语言 AC 代码)
P1439 北京理工大学机试题
发布于 2026年11月
阅读数 14

题意

给字符串,输出其中每个数字字符的位置(从 1 开始,按出现顺序空格分隔)。

思路

  • 遍历字符串,遇到 '0'~'9' 就输出 i+1(1-indexed 位置)。

  • 字符串可能含空格?按整行读取更稳;第一行 m 组。

复杂度

时间 O(L) 每组,空间 O(1)。

参考代码(C / C++ / Java / Python)

C:

#include <stdio.h>
#include <string.h>
static char s[128];
int main(void){int m,i,j;
if(scanf("%d",&m)!=1)return 0;
for(i=0;i<m;i++){
if(scanf("%s",s)!=1)break;
int first=1;
for(j=0;s[j];j++)if(s[j]>='0'&&s[j]<='9'){
if(!first)putchar(' ');
printf("%d",j+1);first=0;}
putchar('\n');}
return 0;}

C++:

#include <iostream>
#include <string>
using namespace std;
int main(){int m;
if(!(cin>>m))return 0;
for(int i=0;i<m;i++){
string s;cin>>s;
bool first=true;
for(size_t j=0;j<s.size();j++)if(s[j]>='0'&&s[j]<='9'){
if(!first)cout<<' ';
cout<<j+1;first=false;}
cout<<"\n";}
return 0;}

Java:

import java.io.*;
import java.util.*;
public class Main{
 public static void main(String[] z) throws IOException{
  BufferedReader br=new BufferedReade...
登录查看完整内容


登录后发布评论

暂无评论,来抢沙发