A simple c++ solution


  • 0
    W
    class Solution {
    	public:
    		bool isSubSequence(string& s1, string& s2) {
    			int i = 0, j = 0;
    			while(i < s1.size()) {
    				while(j < s2.size() && s1[i] != s2[j]) j++;
    				if(j == s2.size()) return false;
    				i++;
    				j++;
    			}
    			return true;
    		}
    		string findLongestWord(string s, vector<string>& d) {
    			int maxLen = 0;
    			int idx = -1;
    			for(int i = 0; i < d.size(); i++) {
    				if(isSubSequence(d[i], s) && (maxLen < d[i].size() || (maxLen == d[i].size() && idx != -1 && d[i] < d[idx]))) {
    					maxLen = d[i].size();
    					idx = i;
    				}
    			}
    			if(idx == -1) return "";
    			return d[idx];
    		}
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.