Home > Article > Web Front-end > Application of strings in javascript (code)
Strings are one of the very important knowledge points in JavaScript. This article lists many examples for you. You can take a look and exercise your abilities.
Make yourself more familiar with the use of each API. The following is the solution to the javascript version of the leetcode question (String entry question group).
Write a function that reverses the input string.
输入: "hello" 输出: "olleh"
输入: "A man, a plan, a canal: Panama" 输出: "amanaP :lanac a ,nalp a ,nam A"
/** * @param {string} s * @return {string} */ var reverseString = function(s) { return s.split('').reverse().join('') };
Common writing methods, convert to array, flip, Change back.
Given a 32-bit signed integer, reverse the digits in the integer.
Note:
Assume that our environment can only store 32-bit signed integers, whose value range is [−231, 231 − 1]. Under this assumption, if the reversed integer overflows, 0 is returned.
输入: 123 输出: 321
输入: -123 输出: -321
输入: 120 输出: 21
/** * @param {number} x * @return {number} */ var _min = Math.pow(-2,31) var _max = Math.pow(2,31) var reverse = function(x) { var _num = null; if(x<0){ _num = Number('-'+(Math.abs(x)+'').split('').reverse().join('')) }else{ _num = Number(((x)+'').split('').reverse().join('')) } if(_num>_max || _num<_min){ return 0; }else{ return _num } };
It looks no different from the first question. Convert to string, flip, turn into numeric value. What needs to be dealt with is the problem of out-of-bounds and positive and negative numbers
Given a string, find it The first non-repeating character and returns its index. If it does not exist, -1 is returned.
Note:
You can assume that the string contains only lowercase letters.
s = "leetcode" 返回 0.
s = "loveleetcode", 返回 2.
/** * @param {string} s * @return {number} */ var firstUniqChar = function(s) { for(var i = 0 ; i < s.length;i++){ if(s.indexOf(s[i]) == s.lastIndexOf(s[i])){ return i } } return -1 };
The solution is not very good and will lead to a lot of traversal times, the idea is to search forward and backward. If the index
is consistent, it proves that there is no repetition
The fastest way is of course to save the current one in the map
, then count, and then traverse it againmap
is ok.
Given two strings s and t, write a function to determine whether t is an anagram of s Position words.
Note:
You can assume that the string contains only lowercase letters.
Advanced:
What if the input string contains unicode characters? Can you adapt your solution to handle this situation?
输入: s = "anagram", t = "nagaram" 输出: true
输入: s = "rat", t = "car" 输出: false
/** * @param {string} s * @param {string} t * @return {boolean} */ var isAnagram = function(s, t) { var _sArr = {}; var _tArr = {}; if(s.length != t.length) return false; for(var i = 0;i<s.length;i++){ if(!_sArr[s[i]]) _sArr[s[i]] = 0; _sArr[s[i]]++ if(!_tArr[t[i]]) _tArr[t[i]] = 0; _tArr[t[i]]++ } for(var i in _sArr){ if(_sArr[i]!=_tArr[i]){ return false; } } return true; };
This is to count and then determine whether the element is All the same amount.
Given a string, verify whether it is a palindrome string. Only alphabetic and numeric characters are considered. Letters can be ignored. uppercase and lowercase.
Explanation:
In this question, we define the empty string as a valid palindrome string.
输入: "A man, a plan, a canal: Panama" 输出: true
输入: "race a car" 输出: false
/** * @param {string} s * @return {boolean} */ var isPalindrome = function(s) { var _s = s.replace(/[^a-z0-9]/gi,'').toLowerCase(); return _s.split('').reverse().join('') == _s };
Delete all unnecessary characters through regular expressions , converted to lowercase, flipped for comparison.
Implement atoi and convert string to integer.
Before finding the first non-empty character, the space characters in the string need to be removed. If the first non-null character is a plus or minus sign, select that sign and combine it with as many consecutive numbers as possible. This part of the character is the value of the integer. If the first non-null character is a number, it is directly combined with subsequent consecutive numeric characters to form an integer.
Strings can include extra characters after the characters that form the integer. These characters can be ignored and have no effect on the function.
When the first non-empty character sequence in the string is not a valid integer; or the string is empty; or the string contains only whitespace characters, no conversion is performed.
If the function cannot perform a valid conversion, return 0.
Note:
Assume that our environment can only store 32-bit signed integers, and the value range is [−231, 231 − 1]. If the value exceeds the representable range, INT_MAX (231 − 1) or INT_MIN (−231) is returned.
输入: "42" 输出: 42
输入: " -42" 输出: -42 解释: 第一个非空白字符为 '-', 它是一个负号。 我们尽可能将负号与后面所有连续出现的数字组合起来,最后得到 -42 。
输入: "4193 with words" 输出: 4193 解释: 转换截止于数字 '3' ,因为它的下一个字符不为数字。
输入: "words and 987" 输出: 0 解释: 第一个非空字符是 'w', 但它不是数字或正、负号。 因此无法执行有效的转换。
输入: "-91283472332" 输出: -2147483648 解释: 数字 "-91283472332" 超过 32 位有符号整数范围。 因此返回 INT_MIN (−231) 。
/** * @param {string} str * @return {number} */ var myAtoi = function(str) { var _num = parseInt(str) || 0 if(_num < (Math.pow(-2,31))){ return (Math.pow(-2,31)) }else if(_num >= (Math.pow(2,31))){ return (Math.pow(2,31)-1) }else{ return _num } };
There is nothing to say about this, judge the boundary, and thenparseInt
Given a haystack string and a needle string, find the first position (starting from 0) where the needle string appears in the haystack string. If it does not exist, -1 is returned.
Explanation:
When needle is an empty string, what value should we return? This is a great question to ask in an interview.
For this question, we should return 0 when needle is an empty string. This is consistent with the definition of strstr() in C and indexOf() in Java.
输入: haystack = "hello", needle = "ll" 输出: 2
输入: haystack = "aaaaa", needle = "bba" 输出: -1
/** * @param {string} haystack * @param {string} needle * @return {number} */ var strStr = function(haystack, needle) { return haystack.indexOf(needle) };
There is nothing to say, regular orindexOf
can be realized
The counting sequence refers to a sequence of integers, and is performed in the order of the integers. Count and get the next number. The first five items are as follows:
1. 1 2. 11 3. 21 4. 1211 5. 111221
1 被读作 "one 1" ("一个一") , 即 11。
11 被读作 "two 1s" ("两个一"), 即 21。
21 被读作 "one 2", "one 1" ("一个二" , "一个一") , 即 1211。
给定一个正整数 n ,输出报数序列的第 n 项。
注意:整数顺序将表示为一个字符串。
输入: 1 输出: "1"
输入: 4 输出: "1211"
/** * @param {number} n * @return {string} */ var countAndSay = function(n) { var _str = '1'; for(var i=1;i<n;i++){ _str = _str.match(/1+|2+|3+|4+|5+|6+|7+|8+|9+/g).map(v=>''+v.length+v[0]).join(''); } return _str };
我的想法是选出连续的同字符,然后把该字符串变成长度加字符,再拼回去
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""。
说明:
所有输入只包含小写字母 a-z 。
输入: ["flower","flow","flight"] 输出: "fl"
输入: ["dog","racecar","car"] 输出: "" 解释: 输入不存在公共前缀。
/** * @param {string[]} strs * @return {string} */ var longestCommonPrefix = function(strs) { var _arr = (strs[0]||'').split('').map((v,i)=>strs[0].slice(0,i+1)).reverse(); for(var i = 1;i<strs.length;i++){ // if(_arr.length == 0) break; while(_arr.length){ var _index = strs[i].indexOf(_arr[0]); if(_index != 0){ _arr.shift() }else{ break; } } } return _arr[0] || '' };
想法是做一个公共前缀数组,遍历,如果有不满足的,就操作这个前缀数组,直到最后,剩下的就是满足的。取最大的一个。
相关推荐:
The above is the detailed content of Application of strings in javascript (code). For more information, please follow other related articles on the PHP Chinese website!