본문 바로가기

Problem Solving/리트코드

[LeetCode] Longest Word in Dictionary through DeletingSolution

중간중간 헷갈려서 조금 헤맸다.

public안에 sort를 위한 bool을 추가했는데 앞에 static을 붙여야 돌아가더라.

왜 붙여야 하는지는 아직 이해 못함.

내가 짠 코드

class Solution {

    
public:
    static bool sortWithLength(string a, string b){
        return a.length()>b.length();
    }
    string findLongestWord(string s, vector<string>& d) {
        string ans;
        int ans_len=0;
        sort(d.begin(),d.end(),sortWithLength);
        int i,j,dPos,sPos;
        for(i=0;i<d.size();i++){
            cout << "string : " << d[i] << endl;
            dPos=0;
            sPos=0;
            while(sPos<s.length() && dPos<d[i].length()){
                if(s[sPos]==d[i][dPos]){
                    sPos++;
                    dPos++;
                }
                else sPos++;
            }
            //cout << "sPos : " << sPos << ", dPos : " << dPos << endl;
            if(dPos==d[i].length()){
                if(dPos>ans_len){
                    ans_len = dPos;
                    ans = d[i];
                }
                else if(dPos==ans_len){
                    if(ans[0]>d[i][0]) ans = d[i]; //같은경우에는 alphabetical 빠른 값을 넣어준다.
                }
                if(ans_len>d[i].length()) return ans;
            }
        }
        return ans;
    }


};

leetcode.com/explore/challenge/card/february-leetcoding-challenge-2021/587/week-4-february-22nd-february-28th/3649/

 

Explore - LeetCode

LeetCode Explore is the best place for everyone to start practicing and learning on LeetCode. No matter if you are a beginner or a master, there are always new topics waiting for you to explore.

leetcode.com

 

'Problem Solving > 리트코드' 카테고리의 다른 글

[LeetCode] Arithmetic SlicesSolution  (0) 2021.02.19
[LeetCode] Linked List Cycle  (0) 2021.02.08
[LeetCode] Number of 1 Bits  (0) 2021.02.08
[LeetCode] Squares of a Sorted Array  (0) 2021.01.29
[LeetCode] 541. Reverse String II  (0) 2021.01.27