top1编程
← 返回题目
题解

【入门】求数字的位置

2 条题解

  • 0
    @ 2026-10-24 8:02:30

    1. 解题思路

    逐组读入不含空格的字符串,依次扫描字符。遇到0到9之间的数字字符,输出该字符的位置i+1。

    2. 坑点和注意事项

    字符串下标从0开始,题目位置从1开始,必须加1。只在后续位置前加分隔空格,避免多余空格;一组没有数字时也要输出该组空行。每组处理完单独换行,最多100组、每串最多50字符,下标用int足够。

    3. 复杂度

    • 时间复杂度:O(L),L为所有字符串长度之和。
    • 空间复杂度:O(k),k为单组字符串长度。
    /*
    思路:逐个字符扫描,遇到数字字符就输出它的位置。
    关键:字符串下标从0开始,而题目位置从1开始。
    坑点:每组单独换行,没有数字时输出空行;分隔空格只放在位置之间。
    时间复杂度:O(L),L为所有字符串长度之和。
    空间复杂度:O(k),k为单个字符串长度;位置下标用int。
    */
    #include <bits/stdc++.h>
    using namespace std;
    int main()
    {
        int m;
        cin >> m;
        while (m--)
        {
            string s;
            bool flag = false;
            cin >> s;
            for (int i = 0; i < (int)s.size(); i++)
            {
                if (s[i] >= '0' && s[i] <= '9')
                {
                    // 首个位置前不加空格,后续位置才加分隔符。
                    if (flag)
                    {
                        cout << " ";
                    }
                    cout << i + 1;
                    flag = true;
                }
            }
            cout << endl;
        }
        return 0;
    }
    
    • 0
      @ 2026-7-28 22:10:13
      #include <bits/stdc++.h>
      using namespace std;
      int main() {
      	string s;
      	int m;
      	cin>>m;
      	for(int i=1;i<=m;i++){
      		cin>>s;
      		for(int j=0;j<s.size();j++){
      			if(s[j]>='0'&&s[j]<='9'){
      				cout<<j+1<<" ";
      			}
      		}
      		cout<<endl;
      	}
      	
      	return 0;
      }
      
      • 1