1. 程式人生 > >某道華為機試題

某道華為機試題

這道題比較簡單,我就直接放題目跟我的解答吧

對輸入的單詞進行字典序排序輸出: 字典序定義 1. 單詞中字母比較不區分大小寫,兩個單詞先以第一個字母作為排序的基準,
如果第一個字母相同,就用第二個字母為基準,如果第二個字母相同就以第三個字母為基準。依此類推,如果到某個字母不相同,
字母順序在前的那個單詞順序在前。 2. 當一個短單詞和一個長單詞的開頭部分都相同(即短單詞是長單詞從首字母開始的一部分),
短單詞順序在前。 3. 字母大小寫不同的相同單詞,只輸出一次。
輸入描述:
不超過255個字元中,單詞間用空格進行分隔,為簡單起見,單詞不包含連字元,無其它標點符號
輸出描述:
輸出排序後的單詞,單詞之間用空格隔開(最後不帶空格),重複的單詞只輸出一次。
示例1
輸入 Hello hello world 輸出 Hello world i LOVE Cc I love CC Hello Hel Hellow
#include <iostream>
#include <string>
#include <vector>
#include <string.h>
#include <algorithm>
#include <iterator>
#include <cctype>
/***
1,思路為存入某一行的資料,利用strtok切分開
2,將切分開的資料匯入查重操作,去掉重複性的資料
3,呼叫sort進行string陣列的字典序排序,注意滿足題意需要在cmp函式裡面用些技巧
***/
using namespace std; char data[255]; //存入控制檯某一行的資料 string str[255]; //儲存切分後的資料 int cmp(string a,string b) { string dst_data,dst_temp; transform(a.begin(), a.end(), back_inserter(dst_data), ::toupper); transform(b.begin(), b.end(), back_inserter(dst_temp), ::toupper); return
dst_data.compare(dst_temp)<0; } int CheckString(char *data,int num){ //解決重複,大小寫問題 string dst_data,dst_temp; string temp = data; transform(temp.begin(), temp.end(), back_inserter(dst_data), ::toupper); for(int i=0;i<num;i++){ dst_temp = ""; string each_str = str[i]; transform(each_str.begin(), each_str.end(), back_inserter(dst_temp), ::toupper); if(dst_data==dst_temp){ return 1; } } return 0; } int main() { int count = 0; cin.getline(data,255); const char * split = " "; char * p; p = strtok (data,split); while(p!=NULL) { if(CheckString(p,count)){ p = strtok(NULL,split); continue; } else{ str[count++] = p; p = strtok(NULL,split); } } sort(str, str+count, cmp); for(int i=0;i<count-1;i++) //格式控制 cout<<str[i]<<" "; cout<<str[count-1]; return 0; }