LeetCode算法笔记–Day3 01.05. 一次编辑 题目:
字符串有三种编辑操作:插入一个字符、删除一个字符或者替换一个字符。 给定两个字符串,编写一个函数判定它们是否只需要一次(或者零次)编辑。
示例1: 输入: first = “pale” second = “ple” 输出: True
示例2: 输入: first = “pales” second = “ple” 输出: false
我的解答: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 var oneEditAway = function(first , second ) { let _long = first .length > second .length ? first .split ("" ) : second .split ("" ); let _short = first .length > second .length ? second .split ("" ) : first .split ("" ); let diffValue = _long.length - _short.length ; let diffAmount = 0 switch(diffValue){ case 0 : if (_long.toString() == _short.toString()){ return true ; }else { _long.map ((res,idx)=>{ if (res != _short[idx]) diffAmount += 1 ; }) return diffAmount > 1 ? false : true } break ; case 1 : for (let idx=0 ;idx < _long.length ; idx++) { if (_long[idx] != _short[idx]){ if (idx == _long.length -1 ){ diffAmount += 1 ; }else { _long.slice(idx+1 ,_long.length ).toString() == _short.slice(idx,_short.length ).toString() ? diffAmount += 1 :diffAmount += 2 ; } break ; } } break ; default: return false ; break ; } return diffAmount > 1 ? false :true };
01.06. 字符串压缩 题目:
字符串压缩。利用字符重复出现的次数,编写一种方法,实现基本的字符串压缩功能。比如,字符串aabcccccaaa会变为a2b1c5a3。若“压缩”后的字符串没有变短,则返回原先的字符串。你可以假设字符串中只包含大小写英文字母(a至z)
示例1: “aabcccccaaa” “a2b1c5a3”
示例2: “abbccd” “abbccd”
我的解答: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 var compressString = function(S) { let result_arr = []; let s_arr = S.split ("" ); let _pointer = 0 ; let repeat_num = 1 ; let repeat_word = S.split ("" )[0 ]; while (_pointer < s_arr.length ){ if (s_arr[_pointer] == s_arr[_pointer+1 ]){ repeat_num += 1 ; repeat_word = s_arr[_pointer]; }else if (s_arr[_pointer] != s_arr[_pointer+1 ] && repeat_num == 1 ){ result_arr.push (s_arr[_pointer]); result_arr.push (1 ); }else { result_arr.push (repeat_word); result_arr.push (repeat_num); repeat_word = null; repeat_num = 1 ; } _pointer += 1 ; } return result_arr.join ("" ).length < S.length ? result_arr.join ("" ) : S };