Is this solution space o(1), time o(n)?


  • 0
    J

    /**

    • Definition for singly-linked list.

    • struct ListNode {

    • int val;
      
    • ListNode *next;
      
    • ListNode(int x) : val(x), next(NULL) {}
      
    • };
      /
      class Solution {
      public:
      bool isPalindrome(ListNode
      head) {
      if(!head || !head->next) return true;
      string s = "";
      while(head != NULL) {
      s += to_string(head->val);
      s += ",";
      head = head->next;
      }
      cout<<s;
      int f1,f2,s1,s2;
      for(int i = 0, j = s.size() - 1;i < j;) {
      f1 = i, s2 = j;
      f2 = i + 1, s1 = j - 1;
      while(s[f2] != ',' && f2 < s.size()) f2++;
      while(s[s1] != ',' && s1 > 0) s1--;
      string str1, str2;
      str1.assign(s.begin() + f1, s.begin() + f2);
      str2.assign(s.begin() + s1 + 1, s.begin() + s2);

           if(str1 != str2) return false;
           i = f2 + 1;
           j = s1;
       }
       return true;
      

      }
      };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.