Longest Common Substring


/ Published in: R
Save to your folder(s)



Copy this code and paste it in your HTML
  1. LenLongStr <- function(String1, String2) {
  2.  
  3. s1 <- unlist(strsplit(String1,split="")) # rozbicie stringu na tablice znakow
  4. s2 <- unlist(strsplit(String2,split=""))
  5.  
  6. num <- matrix(0,nchar(String1),nchar(String2) )
  7. maxlen <- 0
  8.  
  9. for (i in 1:nchar(String1)) {
  10.  
  11. for (j in 1:nchar(String2)) {
  12.  
  13. if (s1[i] == s2[j]) {
  14. if ((i==1) || (j==1)) {
  15. num[i,j] <- 1
  16. }
  17. else {
  18. num[i,j] <- 1+num[i-1,j-1]
  19. }
  20. if (num[i,j] > maxlen) {
  21. maxlen <- num[i,j]
  22. }
  23. }
  24. }
  25. }
  26.  
  27. maxlen
  28. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.