Rumah  >  Artikel  >  hujung hadapan web  >  Struktur data dan algoritma dalam JavaScript (4): String (BF)_javascript kemahiran

Struktur data dan algoritma dalam JavaScript (4): String (BF)_javascript kemahiran

WBOY
WBOYasal
2016-05-16 15:54:101523semak imbas

Rentetan ialah urutan terhingga sifar atau lebih aksara, juga dipanggil rentetan

Struktur logik rentetan sangat serupa dengan jadual linear Perbezaannya ialah rentetan ialah set aksara, jadi operasinya agak berbeza daripada jadual linear. Jadual linear lebih memfokuskan pada operasi CURD bagi satu elemen, manakala rentetan memfokuskan pada operasi seperti mencari kedudukan subrentetan dan menggantikannya.

Sudah tentu, bahasa peringkat tinggi yang berbeza mempunyai takrifan operasi rentetan asas yang berbeza, tetapi secara umum intipati operasi adalah serupa. Sebagai contoh, carian javascript ialah indexOf, penyingkiran kosong adalah trim, penukaran kes kepadaLowerCase/toUpperCase, dsb.

Di sini kita membincangkan terutamanya beberapa algoritma klasik untuk padanan corak rentetan: BF, BM, KMP

Algoritma BF (Brute Force)

Idea asas algoritma Brute-Force:

Bandingkan aksara pertama rentetan sasaran s dengan aksara pertama rentetan corak t Jika ia sama, teruskan bandingkan aksara berikutnya satu demi satu. Jika tidak, mulakan dari aksara kedua rentetan s dan mulakan semula rentetan t. Buat perbandingan.

Dan seterusnya, sehingga setiap aksara dalam rentetan t adalah sama dengan urutan aksara berterusan dalam rentetan s, padanan corak dikatakan berjaya Pada masa ini, kedudukan aksara pertama rentetan t dalam rentetan s ialah kedudukan t dalam s, jika tidak padanan corak gagal


Ia boleh dilihat bahawa algoritma BF ialah algoritma brute force, juga dikenali sebagai algoritma padanan naif atau algoritma brute force.

Rentetan utama BBC ABB ABCF

Subrentetan ABC

Mencari kedudukan subrentetan dalam rentetan utama sepadan dengan pelaksanaan kaedah carian indexOf javascript

var sourceStr = "BBC ABB ABCF";
var searchStr = "ABC";

function BF_Ordinary(sourceStr, searchStr) {
 var sourceLength = sourceStr.length;
 var searchLength = searchStr.length;
 var padding   = sourceLength - searchLength; //循环的次数
 //BBC ABB ABCF =>ABC => 搜索9次
 for (var i = 0; i <= padding; i++) {
  //如果满足了第一个charAt是相等的
  //开始子循环检测
  //其中sourceStr的取值是需要叠加i的值
  if (sourceStr.charAt(i) == searchStr.charAt(0)) {
   //匹配成功的数据
   var complete = searchLength;
   for (var j = 0; j < searchLength; j++) {
    if (sourceStr.charAt(i + j) == searchStr.charAt(j)) {
     --complete
     if (!complete) {
      return i;
     }
    }
   }
  }
 }
 return -1;
}

Algoritma BF adalah ringkas dan kasar Ia terus mengeluarkan jadual di bawah untuk setiap aksara rentetan induk BBC ABB ABCF dan memadankannya dengan aksara pertama rentetan corak Jika sama, rentetan itu dipadankan semula

Perlu diperhatikan di sini:

1: Bilangan kali gelung terluar sourceLength - searchLength, kerana rentetan induk yang kita padankan mestilah sekurang-kurangnya lebih besar daripada atau sama dengan subrentetan

2: Dalam pemadanan subrentetan berterusan, titik permulaan rentetan induk perlu ditindih (i j)

3: Tentukan sama ada ia sepadan dengan lengkap melalui syarat Dalam BBC ABB ABCF, kita perlu melompat apabila kita berada dalam ABB

Di atas ialah algoritma yang paling mudah, dan terdapat kaedah pemprosesan yang lebih baik dalam kod Contohnya, algoritma penyongsangan boleh digunakan untuk memadankan rentetan diri

Algoritma Pengoptimuman (1)

function BF_Optimize(sourceStr, searchStr) {
  var mainLength  = sourceStr.length;
  var searchLength = searchStr.length;
  var padding   = mainLength - searchLength;
  for (var offset = 0; offset <= padding; offset++) {
   var match = true;
   for (var i = 0; i < searchLength; i++) {
    //取反,如果只要不相等
    if (searchStr.charAt(i) !== sourceStr.charAt(offset + i)) {
     match = false;
     break;
    }
   }
   if (match) return offset;
  }
  return -1;
}

Kita tidak perlu menilai situasi itu sebagai benar, kita hanya perlu menilai situasi itu sebagai palsu Apabila perlawanan tidak diubah suai selepas sub-perlawanan selesai, bermakna perlawanan itu adalah perlawanan yang lengkap

Kami telah menggunakan sub-gelung dalam dua kaedah di atas. Bolehkah kami menukarnya menjadi badan gelung?

Malah, kita dapat melihat corak Rentetan utama hanya akan meningkat sebanyak 1 setiap kali, dan subrentetan akan dipadankan dari awal setiap kali, jadi kita boleh menukarnya seketika dan mengawal penunjuk subskrip 🎜>

Algoritma Pengoptimuman (2)


function BF_Optimize_2(sourceStr, searchStr) {
 var i = 0,
   j = 0;

  while (i < sourceStr.length) {
    // 两字母相等则继续 
    if (sourceStr.charAt(i) == searchStr.charAt(j)) {
     i++;
     j++;
    } else { // 两字母不等则角标后退重新开始匹配 
     i = i - j + 1; // i 回退到上次匹配首位的下一位 
     j = 0; // j 回退到子串的首位 
    }

    if (j == searchStr.length) {
     return i - j;
    }

  }
}

i ialah kedudukan subskrip bagi rentetan utama, j ialah kedudukan subskrip bagi rentetan itu

Apabila rentetan utama dan subrentetan adalah sama, ia memasuki mod gelung subrentetan Apabila bilangan subgelung j memenuhi panjang subrentetan, ia disahkan bahawa ia adalah padanan lengkap

Apabila rentetan utama dan subrentetan tidak sama, anda perlu mengalihkan subskrip rentetan utama ke belakang satu bit Sudah tentu, apabila i digunakan, ia mungkin diproses oleh subrentetan, jadi i-j 1 diperlukan, dan kemudian subrentetan ditetapkan semula

Untuk butiran, kita boleh melihat perbandingan kod

Empat struktur berdasarkan algoritma BF, untuk/semasa/rekursi


<!doctype html>由于电脑性能的不断提高,测试的数据量的大小,可能会导致得到的结果不太准确;<script type="text/javascript">

 /////////
 //暴力算法 //
 //普通版
 /////////
 function BF_Ordinary(sourceStr, searchStr) {
  var sourceLength = sourceStr.length;
  var searchLength = searchStr.length;
  var padding   = sourceLength - searchLength; //循环的次数

  //BBC ABB ABCF =>ABC => 搜索9次
  for (var i = 0; i <= padding; i++) {
   //如果满足了第一个charAt是相等的
   //开始子循环检测
   //其中sourceStr的取值是需要叠加i的值
   if (sourceStr.charAt(i) == searchStr.charAt(0)) {
    //匹配成功的数据
    var complete = searchLength;
    for (var j = 0; j < searchLength; j++) {
     if (sourceStr.charAt(i + j) == searchStr.charAt(j)) {
      --complete
      if (!complete) {
       return i;
      }
     }
    }
   }
  }
  return -1;
 }


 /////////
 //暴力算法 //
 //优化版
 /////////
 function BF_Optimize_1(sourceStr, searchStr) {
   var mainLength  = sourceStr.length;
   var searchLength = searchStr.length;
   var padding   = mainLength - searchLength;
   for (var offset = 0; offset <= padding; offset++) {
    var match = true;
    for (var i = 0; i < searchLength; i++) {
     //取反,如果只要不相等
     if (searchStr.charAt(i) !== sourceStr.charAt(offset + i)) {
      match = false;
      break;
     }
    }
    if (match) return offset;
   }
   return -1;
 }


  ////////
  //优化版 //
  //while
  ////////
 function BF_Optimize_2(sourceStr, searchStr) {
  var i = 0,
    j = 0;

   while (i < sourceStr.length) {
     // 两字母相等则继续 
     if (sourceStr.charAt(i) == searchStr.charAt(j)) {
      i++;
      j++;
     } else { // 两字母不等则角标后退重新开始匹配 
      i = i - j + 1; // i 回退到上次匹配首位的下一位 
      j = 0; // j 回退到子串的首位 
     }

     if (j == searchStr.length) {
      return i - j;
     }

   }
 }


 /////////
 //暴力算法
 //递归版本
 /////////
 function BF_Recursive(sourceStr, searchStr, offset) {
   var mainLength = sourceStr.length;
   var searchLength = searchStr.length;
   if (searchLength > mainLength - offset) {
    return -1;
   }
   offset = offset || 0;
   for (var i = 0; searchLength > i; i++) {
    if (searchStr.charAt(i) !== sourceStr.charAt(offset + i)) {
     return BF_Recursive(sourceStr, searchStr, offset + 1)
    }
   }
   return offset;
 }


 
 var sourceStr = "There are some times wThere are some times when clicking “like” on a friend's Facebook status doesn't feel appropriate. A bad day. A loved one lost. A break up. It only seems natural that a “dislike” button could solve the conundrum of wanting to empathize but not seem inappropriate by clicking “like.” Mark Zuckerberg Puts the Rest of Us to Shame by Speaking Fluent Chinese. Mark Zuckerberg: Facebook Founder and Animal Butcher. Mark Zuckerberg and That Shirt. The idea has been on Mark Zuckerberg's radar for a while, he said. In 2010, he told ABC News' Diane Sawyer that that Facebook would “definitely thinkThere are some times when clicking “like” on a friend's Facebook status doesn't feel appropriate. A bad day. A loved one lost. A break up. It only seems natural that a “dislike” button could solve the conundrum of wanting to empathize but not seem inappropriate by clicking “like.” Mark Zuckerberg Puts the Rest of Us to Shame by Speaking Fluent Chinese. Mark Zuckerberg: Facebook Founder and Animal Butcher. Mark Zuckerberg and That Shirt. The idea has been on Mark Zuckerberg's radar for a while, he said. In 2010, he told ABC News' Diane Sawyer that that Facebook would “definitely thinkThere are some times when clicking “like” on a friend's Facebook status doesn't feel appropriate. A bad day. A loved one lost. A break up. It only seems natural that a “dislike” button could solve the conundrum of wanting to empathize but not seem inappropriate by clicking “like.” Mark Zuckerberg Puts the Rest of Us to Shame by Speaking Fluent Chinese. Mark Zuckerberg: Facebook Founder and Animal Butcher. Mark Zuckerberg and That Shirt. The idea has been on Mark Zuckerberg's radar for a while, he said. In 2010, he told ABC News' Diane Sawyer that that Facebook would “definitely thinkThere are some times when clicking “like” on a friend's Facebook status doesn't feel appropriate. A bad day. A loved one lost. A break up. It only seems natural that a “dislike” button could solve the conundrum of wanting to empathize but not seem inappropriate by clicking “like.” Mark Zuckerberg Puts the Rest of Us to Shame by Speaking Fluent Chinese. Mark Zuckerberg: Facebook Founder and Animal Butcher. Mark Zuckerberg and That Shirt. The idea has been on Mark Zuckerberg's radar for a while, he said. In 2010, he told ABC News' Diane Sawyer that that Facebook would “definitely thinkThere are some times when clicking “like” on a friend's Facebook status doesn't feel appropriate. A bad day. A loved one lost. A break up. It only seems natural that a “dislike” button could solve the conundrum of wanting to empathize but not seem inappropriate by clicking “like.” Mark Zuckerberg Puts the Rest of Us to Shame by Speaking Fluent Chinese. Mark Zuckerberg: Facebook Founder and Animal Butcher. Mark Zuckerberg and That Shirt. The idea has been on Mark Zuckerberg's radar for a while, he said. In 2010, he told ABC News' Diane Sawyer that that Facebook would “definitely thinkThere are some times when clicking “like” on a friend's Facebook status doesn't feel appropriate. A bad day. A loved one lost. A break up. It only seems natural that a “dislike” button could solve the conundrum of wanting to empathize but not seem inappropriate by clicking “like.” Mark Zuckerberg Puts the Rest of Us to Shame by Speaking Fluent Chinese. Mark Zuckerberg: Facebook Founder and Animal Butcher. Mark Zuckerberg and That Shirt. The idea has been on Mark Zuckerberg's radar for a while, he said. In 2010, he told ABC News' Diane Sawyer that that Facebook would “definitely thinkhen clicking “like” on a friend's Facebook status doesn't feel appropriate. A bad day. A loved one lost. A break up. It only seems natural that a “dislike” button could solve the conundrum of wanting to empathize but not seem inappropriate by clicking “like.” Mark Zuckerberg Puts the Rest of Us to Shame by Speaking Fluent Chinese. Mark Zuckerberg: Facebook Founder and Animal Butcher. Mark Zuckerberg and That Shirt. The idea has been on Mark Zuckerberg's radar for a while, he said. In 2010, he told ABC News' Diane Sawyer There are some times when clicking “like” on a friend's Facebook status doesn't feel appropriate. A bad day. A loved one lost. A break up. It only seems natural that a “dislike” button could solve the conundrum of wanting to empathize but not seem inappropriate by clicking “like.” Mark Zuckerberg Puts the Rest of Us to Shame by Speaking Fluent Chinese. Mark Zuckerberg: Facebook Founder and Animal Butcher. Mark Zuckerberg and That Shirt. The idea has been on Mark Zuckerberg's radar for a while, he said. In 2010, he told ABC News' Diane Sawyer that that Facebook would “definitely thinkThere are some times when clicking “like” on a friend's Facebook status doesn't feel appropriate. A bad day. A loved one lost. A break up. It only seems natural that a “dislike” button could solve the conundrum of wanting to empathize but not seem inappropriate by clicking “like.” Mark Zuckerberg Puts the Rest of Us to Shame by Speaking Fluent Chinese. Mark Zuckerberg: Facebook Founder and Animal Butcher. Mark Zuckerberg and That Shirt. The idea has been on Mark Zuckerberg's radar for a while, he said. In 2010, he told ABC News' Diane Sawyer that that Facebook would “definitely thinkThere are some times when clicking “like” on a friend's Facebook status doesn't feel appropriate. A bad day. A loved one lost. A break up. It only seems natural that a “dislike” button could solve the conundrum of wanting to empathize but not seem inappropriate by clicking “like.” Mark Zuckerberg Puts the Rest of Us to Shame by Speaking Fluent Chinese. Mark Zuckerberg: Facebook Founder and Animal Butcher. Mark Zuckerberg and That Shirt. The idea has been on Mark Zuckerberg's radar for a while, he said. In 2010, he told ABC News' Diane Sawyer that that Facebook would “definitely thinkThere are some times when clicking “like” on a friend's Facebook status doesn't feel appropriate. A bad day. A loved one lost. A break up. It only seems natural that a “dislike” button could solve the conundrum of wanting to empathize but not seem inappropriate by clicking “like.” Mark Zuckerberg Puts the Rest of Us to Shame by Speaking Fluent Chinese. Mark Zuckerberg: Facebook Founder and Animal Butcher. Mark Zuckerberg and That Shirt. The idea has been on Mark Zuckerberg's radar for a while, he said. In 2010, he told ABC News' Diane Sawyer that that Facebook would “definitely think that that Facebook would “definitely think about” adding a dislike button. “People definitely seem to want it,” Zuckerberg said. Four years later — Zuckerberg says Facebook is still “thinking about” adding the oft-requested sdfafd button, Zuckerberg says Facebook is still “thinking about” adding the oft-requested button. At a town hall meeting on Thursday, the CEO revealed he has some reservations about the feature. “There are two things that it can mean,” Zuckerberg said of the potential button, which could be used in a mean spirited way or to express empathy. Finding how to limit it to the latter is the challenge. Zuckerberg said he doesn't want the button to turn into a “voting mechanism” or something that isn't “socially valuable.” “Often people will tell us they don't feel comfortable pressing ‘like,'” Zuckerberg said. “What's the right way to make it so people can easier express a wide range of emotions&#63;” One suggestion percolating online: Aaron Roll out the feature under a different name. However, an “empathy button” just may not have the same ring to it as “dislike.”";
 var searchStr = "adding the oft-requested sdf";



 function show(bf_name,fn) {
  var myDate = +new Date()
  var r = fn();
  var div = document.createElement('div')
  div.innerHTML = bf_name +'算法,搜索位置:' + r + ",耗时" + (+new Date() - myDate) + "ms";
  document.body.appendChild(div);
 }

 show('BF_Ordinary',function() {
  return BF_Ordinary(sourceStr, searchStr)
 })

 show('BF_Optimize_1',function() {
  return BF_Optimize_1(sourceStr, searchStr)
 })

 show('BF_Optimize_2',function() {
  return BF_Optimize_2(sourceStr, searchStr)
 })

 show('BF_Recursive',function() {
  return BF_Recursive(sourceStr, searchStr)
 })

</script>
BF juga merupakan algoritma pemadanan awalan klasik. Awalan ini juga termasuk KMP. Kita dapat melihat bahawa kelemahan terbesar algoritma ini ialah penunjuk mesti diundur jika padanan aksara gagal, jadi saya akan melakukannya tulis tentang peningkatan algoritma KMP dan BM untuk BF nanti
muat turun kod git:

https://github.com/JsAaron/data_structure

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn