image.png解:

思路:遍历dictionary ,再使用双指针,挨个比较成员和s。然后将长度最长的存储下来

  1. let s = "abce", dictionary = ["abe", "abc"]
  2. var findLongestWord = function (s, dictionary) {
  3. let res = ''
  4. dictionary.forEach(val => {
  5. let len = s.length - 1, len1 = val.length - 1
  6. while (len >= 0) {
  7. if (s[len] === val[len1]) {
  8. len1--;
  9. len--;
  10. } else {
  11. len--
  12. }
  13. }
  14. if (len1 === -1) {
  15. if ((res.length < val.length || (val.length === res.length && val < res))) {
  16. res = val
  17. }
  18. }
  19. })
  20. return res
  21. };
  22. console.log(findLongestWord(s, dictionary));