Home > Web Front-end > JS Tutorial > body text

Application of strings in javascript (code)

不言
Release: 2018-09-07 15:06:35
Original
1482 people have browsed it

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).

1. Reverse the string

Instructions

Write a function that reverses the input string.

Example 1:

输入: "hello"
输出: "olleh"
Copy after login

Example 2:

输入: "A man, a plan, a canal: Panama"
输出: "amanaP :lanac a ,nalp a ,nam A"
Copy after login

Implementation

/**
 * @param {string} s
 * @return {string}
 */
var reverseString = function(s) {
    return s.split('').reverse().join('')
};
Copy after login

Comments

Common writing methods, convert to array, flip, Change back.

2. Reverse integers

Instructions

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.

Example 1:

输入: 123
输出: 321
Copy after login

Example 2:

输入: -123
输出: -321
Copy after login

Example 3:

输入: 120
输出: 21
Copy after login

Implementation

/**
 * @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(&#39;-&#39;+(Math.abs(x)+&#39;&#39;).split(&#39;&#39;).reverse().join(&#39;&#39;))
    }else{
       _num =  Number(((x)+&#39;&#39;).split(&#39;&#39;).reverse().join(&#39;&#39;))
    }
    if(_num>_max || _num<_min){
        return 0;   
    }else{
        return _num
    }
};
Copy after login

Comments

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

3. The first unique character in the string

Description

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.

Case 1:

s = "leetcode"
返回 0.
Copy after login

Case 2:

s = "loveleetcode",
返回 2.
Copy after login

Implementation

/**
 * @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
};
Copy after login

Comments

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.

4. Valid letter anagrams

Explanation

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?

Example 1:

输入: s = "anagram", t = "nagaram"
输出: true
Copy after login

Example 2:

输入: s = "rat", t = "car"
输出: false
Copy after login

Scheme

/**
 * @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;
};
Copy after login

Comments

This is to count and then determine whether the element is All the same amount.

5. Verify palindrome string

Instructions

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.

Example 1:

输入: "A man, a plan, a canal: Panama"
输出: true
Copy after login

Example 2:

输入: "race a car"
输出: false
Copy after login

Plan

/**
 * @param {string} s
 * @return {boolean}
 */
var isPalindrome = function(s) {
    var _s = s.replace(/[^a-z0-9]/gi,&#39;&#39;).toLowerCase();
    return _s.split(&#39;&#39;).reverse().join(&#39;&#39;) == _s
};
Copy after login

Comments

Delete all unnecessary characters through regular expressions , converted to lowercase, flipped for comparison.

6. Convert string to integer (atoi)

Description

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.

Example 1:

输入: "42"
输出: 42
Copy after login

Example 2:

输入: "   -42"
输出: -42
解释: 第一个非空白字符为 &#39;-&#39;, 它是一个负号。
     我们尽可能将负号与后面所有连续出现的数字组合起来,最后得到 -42 。
Copy after login

Example 3:

输入: "4193 with words"
输出: 4193
解释: 转换截止于数字 &#39;3&#39; ,因为它的下一个字符不为数字。
Copy after login

Example 4:

输入: "words and 987"
输出: 0
解释: 第一个非空字符是 &#39;w&#39;, 但它不是数字或正、负号。
     因此无法执行有效的转换。
Copy after login

Example 5

输入: "-91283472332"
输出: -2147483648
解释: 数字 "-91283472332" 超过 32 位有符号整数范围。 
     因此返回 INT_MIN (−231) 。
Copy after login

Plan

/**
 * @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
    }
};
Copy after login

Comments

There is nothing to say about this, judge the boundary, and thenparseInt

7. Implement strStr()

Explanation

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.

Example 1:

输入: haystack = "hello", needle = "ll"
输出: 2
Copy after login

Example 2:

输入: haystack = "aaaaa", needle = "bba"
输出: -1
Copy after login

Plan

/**
 * @param {string} haystack
 * @param {string} needle
 * @return {number}
 */
var strStr = function(haystack, needle) {
    return haystack.indexOf(needle)
};
Copy after login

Comments

There is nothing to say, regular orindexOf can be realized

8. Count and say

Explanation

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
Copy after login

1 被读作  "one 1"  ("一个一") , 即 11。
 11 被读作 "two 1s" ("两个一"), 即 21。
 21 被读作 "one 2",  "one 1" ("一个二" ,  "一个一") , 即 1211。

给定一个正整数 n ,输出报数序列的第 n 项。
 注意:整数顺序将表示为一个字符串。

示例 1:

输入: 1
输出: "1"
Copy after login

示例 2:

输入: 4
输出: "1211"
Copy after login

方案

/**
 * @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
};
Copy after login

点评

我的想法是选出连续的同字符,然后把该字符串变成长度加字符,再拼回去

9. 最长公共前缀

说明

编写一个函数来查找字符串数组中的最长公共前缀。
 如果不存在公共前缀,返回空字符串 ""。

说明:
 所有输入只包含小写字母 a-z 。

示例 1:

输入: ["flower","flow","flight"]
输出: "fl"
Copy after login

示例 2:

输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。
Copy after login

方案

/**
 * @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] || ''
};
Copy after login

点评

想法是做一个公共前缀数组,遍历,如果有不满足的,就操作这个前缀数组,直到最后,剩下的就是满足的。取最大的一个。

相关推荐:

JavaScript中的字符串操作

JavaScript计算字符串中每个字符出现的次数

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template