Weekly Contest 97 (-2)

版权声明:欢迎指出文章不足之处~~~ https://blog.csdn.net/zhui_xiuge/article/details/81639131

1. 888. 两句话中的不常见单词

分析 :需要将句子中所有单词存放起来,同时另存只出现一次的单词

class Solution {
public:
    
    void get_words(string T, vector<string>& x,  vector<string>& words) {
        //
        int front = 0;
        for(int i = 0; i < T.length(); i++) {
            if(T[i] == ' ') {
                words.push_back(T.substr(front, i-front));
                front = i+1;
            }
        }
        if(T.length()) words.push_back(T.substr(front, T.length()-front));
        //
        for(int i = 0; i < words.size(); i++) {
            int repeat = 0;
            for(int j = 0; j < words.size(); j++) {
                if(words[i] == words[j]) repeat++;
            }
            if(repeat == 1) x.push_back(words[i]);
        }
    }
    
    void match(vector<string> x, vector<string> words, vector<string>& ans) { //&
        for(int i = 0; i < x.size(); i++) {
            int index = -1;
            for(int j = 0; j < words.size(); j++) {
                if(x[i] == words[j])  {
                    index = i;
                    break;
                }
            }
            if(index == -1) ans.push_back(x[i]);
        }
    }
    
    vector<string> uncommonFromSentences(string A, string B) {
        vector<string> ans, _A, _B, wordsA, wordsB;
        get_words(A, _A, wordsA);
        get_words(B, _B, wordsB);
        if(wordsA.empty()) ans = _B;
        else if(wordsB.empty()) ans = _A;
        else {
            match(_A, wordsB, ans);
            match(_B, wordsA, ans);    
        }
        return ans;
    }
};

2. 889. 螺旋矩阵 III

分析 :模拟,完整走完两个方向步长就要增1,在某个方向走的时候,如果位置属于格子里,就应当记录到最终的vector

//const int dir[][2]={0,1,1,0,0,-1,-1,0};
const int dr[4] = {0, 1, 0, -1}, dc[4] = {1, 0, -1, 0}; 
class Solution {
public:
    vector<vector<int>> spiralMatrixIII(int R, int C, int r0, int c0) {
        vector<vector<int>> ans;
        vector<int> e(2); //
        int s = R*C, cnt = 0;
        int step = 1;
        int r = r0, c = c0;
        e[0] = r, e[1] = c;
        ans.push_back(e), cnt++;
        while(true) {
           for(int i = 0; i < 4; i++) {
               int _step = 0;
               while(_step < step) {
                   r += dr[i], c += dc[i];        
                   _step++;
                   if(r <= -1 || r >= R || c <= -1 || c >= C) //越界, 加不等号是因为可能不贴着网格外行走(如示例 1)
                       continue; //此处用continue是因为可能在网格之外行走
                   e[0] = r, e[1] = c;
                   ans.push_back(e), cnt++;
               }
               if(cnt == s) break;
               if(i == 1 || i == 3) step++; //
           }
           if(cnt == s) break;
        }
        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/zhui_xiuge/article/details/81639131