記錄一些js面試題以及解法

記錄一些js面試題,解法,感悟。面試

1.將字符串"aaaabbbbcccc"轉換"4a4b4c"數組

  • 解法1
var str = "aaaabbbbcccc"
var reg = /([a-z])\1+/ig
var newStr = str.replace(reg,function(item){
    return item.length+item[0]
})
console.log(newStr)
複製代碼
  • 解法2
var str = "aaaabbbbcccc"
var newStr = ""
var num = 1
for(var i=0;i<str.length;i++){
    if((str[i]==str[i+1])){
        num++
    }else{
        newStr=newStr + num + str[i]
        num=1
    }
}
複製代碼

1.將字符串"4a4b4c"轉換"aaaabbbbcccc"bash

  • 解法1
var str = "4a4b4c"
var reg = /(\d+)([a-z])/ig
var newStr = str.replace(reg,function(item){
    item.match(reg)
    var str = ""
    for(var i=0;i<parseInt(RegExp.$1);i++){
       str+=RegExp.$2 
    }
    return str
})
console.log(newStr)
複製代碼
  • 解法2
var str = "4a4b4c"
var newStr = ""
var mark = 0
for(var i=0;i<str.length;i++){
    if(str[i]>'9'){
        var s = str.slice(mark,i+1)
        for(var j=0;j<parseInt(s);j++){
            newStr+=s[s.length-1]
        }
        mark=i+1
    }
}
複製代碼

2.統計字符串"aaaabbbbcccc"中各個字符出現的次數,好比a出現4次,b出現了4次,c出現了4次ui

  • 解法1
var str = "aaaabbbbcccc"
var reg = /([a-z])\1+/ig
var newStr = ""
str.replace(reg,function(item){
    newStr+=item[0]+'出現了'+item.length+'次,'
})
console.log(newStr)
複製代碼
  • 解法2
var str = "aaaabbbbcccc"
var newStr = ""
var obj = {}
for(var i=0;i<str.length;i++){
   if(obj[str[i]]){
       obj[str[i]]++
   }else{
       obj[str[i]]=1
   }
}
console.log(obj)
複製代碼

3.[1,4,2,4,2,4,1,2]數組排序spa

  • 解法1 通常排序
var arr = [1,4,2,4,2,4,1,2]
for(var i=0;i<arr.length;i++){
	for(var j=i+1;j<arr.length;j++){
		if(arr[j]>arr[i]){
			var m = arr[i]
			arr[i] = arr[j]
			arr[j] = m
		}
	}
}
console.log(arr)
複製代碼
  • 解法2 冒泡排序
var arr = [1,4,2,4,2,4,1,2]
for(var i=0;i<arr.length;i++){
    for(var j=0;j<arr.length-i-1;j++){
        if(arr[j]>arr[j+1]){
            var m = arr[j]
            arr[j] = arr[j+1]
            arr[j+1] = m
        }
    }
}
console.log(arr)
複製代碼
  • 解法3 快速排序(二分排序)
var arr = [1,4,2,4,2,4,1,2] 
function quickSrot(arr) {
    if (arr.length <= 1) {
      return arr
    }
    var middleIndex = Math.floor(arr.length / 2)
    var middle = arr[middleIndex]
    var left = []
    var right = []
    for (var i = 0; i < arr.length; i++) {
      if (arr[i] <= middle) {
        left.push(arr[i])
      } else {
        right.push(arr[i])
      }
    }
    if (left.length == arr.length) {
      left.splice(middleIndex,1)
      right.push(middle)
    }

    if (right.length == arr.length) {
      right.splice(middleIndex,1)
      left.push(middle)
    }

    return quickSrot(left).concat(quickSrot(right))
  }
  quickSrot(arr)
複製代碼

處理字符串仍是用正則比較方便,固然用循環也是能夠的。 ing。。。code

相關文章
相關標籤/搜索