首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

UVA 10361 Automatic Poetry:字符串模擬提取與重組

     編輯:關於C++

題目簡介

輸入兩行字符串。第一行包含 '<' 和 '>' 符號,格式為 s1<s2>s3<s4>s5。第二行以 "..." 結尾。輸出兩行:第一行去掉 '<>' 後的完整字符串;第二行為第二行去掉 "..." 後接上 s4+s3+s2+s5。

解題思路

直接模擬解析:遍歷第一行字符,遇到 '<' '>' 切換狀態,分別提取 s2, s3, s4, s5,同時構建去標記後的字符串。第二行讀取直到空格,去掉末尾 "...",拼接輸出。

代碼實現

#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;

int main() {
    int n; scanf("%d", &n); getchar();
    while (n--) {
        char c, str1[105], str2[105], s2[105], s3[105], s4[105], s5[105];
        int i=0, j=0, f=0;
        while ((c=getchar())!=' ') {
            if (c=='<' && f==0) { f=1; j=0; continue; }
            if (c=='>' && f==1) { f=2; s2[j]='\0'; j=0; continue; }
            if (c=='<' && f==2) { f=3; s3[j]='\0'; j=0; continue; }
            if (c=='>' && f==3) { f=4; s4[j]='\0'; j=0; continue; }
            str1[i++] = c;
            if (f==1) s2[j++] = c;
            else if (f==2) s3[j++] = c;
            else if (f==3) s4[j++] = c;
            else if (f==4) s5[j++] = c;
        }
        s5[j] = str1[i] = '\0';
        i=0;
        while ((c=getchar())!=' ') if (c!='.') str2[i++] = c;
        str2[i] = '\0';
        printf("%s\n", str1);
        printf("%s%s%s%s%s\n", str2, s4, s3, s2, s5);
    }
    return 0;
}

複雜度分析

線性掃描,時間 O(L),L 為字符串長度,極快。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved